file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
sequence | attention_mask
sequence | labels
sequence |
---|---|---|---|---|---|---|
// SPDX-License-Identifier: GPL-3.0-only
pragma experimental ABIEncoderV2;
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.6.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].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: contracts/network/$.sol
pragma solidity ^0.6.0;
/**
* @dev This library is provided for conveniece. It is the single source for
* the current network and all related hardcoded contract addresses. It
* also provide useful definitions for debuging faultless code via events.
*/
library $
{
address constant GRO = 0x09e64c2B61a5f1690Ee6fbeD9baf5D6990F8dFd0;
address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address constant cDAI = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643;
address constant cUSDC = 0x39AA39c021dfbaE8faC545936693aC917d5E7563;
address constant cETH = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address constant COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
address constant Aave_AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119;
address constant Aave_AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
address constant Balancer_FACTORY = 0x9424B1412450D0f8Fc2255FAf6046b98213B76Bd;
address constant Compound_COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address constant Dydx_SOLO_MARGIN = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
address constant Sushiswap_ROUTER02 = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F;
}
// File: contracts/interop/WrappedEther.sol
pragma solidity ^0.6.0;
interface WETH is IERC20
{
function deposit() external payable;
function withdraw(uint256 _amount) external;
}
// File: contracts/interop/UniswapV2.sol
pragma solidity ^0.6.0;
interface Router01
{
function WETH() external pure returns (address _token);
function swapExactTokensForTokens(uint256 _amountIn, uint256 _amountOutMin, address[] calldata _path, address _to, uint256 _deadline) external returns (uint256[] memory _amounts);
function swapETHForExactTokens(uint256 _amountOut, address[] calldata _path, address _to, uint256 _deadline) external payable returns (uint256[] memory _amounts);
function getAmountsOut(uint256 _amountIn, address[] calldata _path) external view returns (uint[] memory _amounts);
function getAmountsIn(uint256 _amountOut, address[] calldata _path) external view returns (uint[] memory _amounts);
}
interface Router02 is Router01
{
}
// File: contracts/interop/Aave.sol
pragma solidity ^0.6.0;
interface LendingPoolAddressesProvider
{
function getLendingPool() external view returns (address _pool);
function getLendingPoolCore() external view returns (address payable _lendingPoolCore);
}
interface LendingPool
{
function getReserveData(address _reserve) external view returns (uint256 _totalLiquidity, uint256 _availableLiquidity, uint256 _totalBorrowsStable, uint256 _totalBorrowsVariable, uint256 _liquidityRate, uint256 _variableBorrowRate, uint256 _stableBorrowRate, uint256 _averageStableBorrowRate, uint256 _utilizationRate, uint256 _liquidityIndex, uint256 _variableBorrowIndex, address _aTokenAddress, uint40 _lastUpdateTimestamp);
function flashLoan(address _receiver, address _reserve, uint256 _amount, bytes calldata _params) external;
}
interface FlashLoanReceiver
{
function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external;
}
// File: contracts/interop/Dydx.sol
pragma solidity ^0.6.0;
interface SoloMargin
{
function getMarketTokenAddress(uint256 _marketId) external view returns (address _token);
function getNumMarkets() external view returns (uint256 _numMarkets);
function operate(Account.Info[] memory _accounts, Actions.ActionArgs[] memory _actions) external;
}
interface ICallee
{
function callFunction(address _sender, Account.Info memory _accountInfo, bytes memory _data) external;
}
library Account
{
struct Info {
address owner;
uint256 number;
}
}
library Actions
{
enum ActionType { Deposit, Withdraw, Transfer, Buy, Sell, Trade, Liquidate, Vaporize, Call }
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
}
library Types
{
enum AssetDenomination { Wei, Par }
enum AssetReference { Delta, Target }
struct AssetAmount {
bool sign;
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
}
// File: contracts/interop/Balancer.sol
pragma solidity ^0.6.0;
interface BFactory
{
function newBPool() external returns (address _pool);
}
interface BPool is IERC20
{
function getFinalTokens() external view returns (address[] memory _tokens);
function getBalance(address _token) external view returns (uint256 _balance);
function setSwapFee(uint256 _swapFee) external;
function finalize() external;
function bind(address _token, uint256 _balance, uint256 _denorm) external;
function exitPool(uint256 _poolAmountIn, uint256[] calldata _minAmountsOut) external;
function joinswapExternAmountIn(address _tokenIn, uint256 _tokenAmountIn, uint256 _minPoolAmountOut) external returns (uint256 _poolAmountOut);
}
// File: contracts/interop/Compound.sol
pragma solidity ^0.6.0;
interface Comptroller
{
function oracle() external view returns (address _oracle);
function enterMarkets(address[] calldata _ctokens) external returns (uint256[] memory _errorCodes);
function markets(address _ctoken) external view returns (bool _isListed, uint256 _collateralFactorMantissa);
function getAccountLiquidity(address _account) external view returns (uint256 _error, uint256 _liquidity, uint256 _shortfall);
}
interface PriceOracle
{
function getUnderlyingPrice(address _ctoken) external view returns (uint256 _price);
}
interface CToken is IERC20
{
function underlying() external view returns (address _token);
function exchangeRateStored() external view returns (uint256 _exchangeRate);
function borrowBalanceStored(address _account) external view returns (uint256 _borrowBalance);
function exchangeRateCurrent() external returns (uint256 _exchangeRate);
function getCash() external view returns (uint256 _cash);
function borrowBalanceCurrent(address _account) external returns (uint256 _borrowBalance);
function balanceOfUnderlying(address _owner) external returns (uint256 _underlyingBalance);
function mint() external payable;
function mint(uint256 _mintAmount) external returns (uint256 _errorCode);
function repayBorrow() external payable;
function repayBorrow(uint256 _repayAmount) external returns (uint256 _errorCode);
function redeemUnderlying(uint256 _redeemAmount) external returns (uint256 _errorCode);
function borrow(uint256 _borrowAmount) external returns (uint256 _errorCode);
}
// File: contracts/modules/Math.sol
pragma solidity ^0.6.0;
library Math
{
function _min(uint256 _amount1, uint256 _amount2) internal pure returns (uint256 _minAmount)
{
return _amount1 < _amount2 ? _amount1 : _amount2;
}
function _max(uint256 _amount1, uint256 _amount2) internal pure returns (uint256 _maxAmount)
{
return _amount1 > _amount2 ? _amount1 : _amount2;
}
}
// File: contracts/modules/Wrapping.sol
pragma solidity ^0.6.0;
library Wrapping
{
function _wrap(uint256 _amount) internal returns (bool _success)
{
try WETH($.WETH).deposit{value: _amount}() {
return true;
} catch (bytes memory /* _data */) {
return false;
}
}
function _unwrap(uint256 _amount) internal returns (bool _success)
{
try WETH($.WETH).withdraw(_amount) {
return true;
} catch (bytes memory /* _data */) {
return false;
}
}
function _safeWrap(uint256 _amount) internal
{
require(_wrap(_amount), "wrap failed");
}
function _safeUnwrap(uint256 _amount) internal
{
require(_unwrap(_amount), "unwrap failed");
}
}
// File: contracts/modules/Transfers.sol
pragma solidity ^0.6.0;
library Transfers
{
using SafeERC20 for IERC20;
function _getBalance(address _token) internal view returns (uint256 _balance)
{
return IERC20(_token).balanceOf(address(this));
}
function _approveFunds(address _token, address _to, uint256 _amount) internal
{
uint256 _allowance = IERC20(_token).allowance(address(this), _to);
if (_allowance > _amount) {
IERC20(_token).safeDecreaseAllowance(_to, _allowance - _amount);
}
else
if (_allowance < _amount) {
IERC20(_token).safeIncreaseAllowance(_to, _amount - _allowance);
}
}
function _pullFunds(address _token, address _from, uint256 _amount) internal
{
IERC20(_token).safeTransferFrom(_from, address(this), _amount);
}
function _pushFunds(address _token, address _to, uint256 _amount) internal
{
IERC20(_token).safeTransfer(_to, _amount);
}
}
// File: contracts/modules/SushiswapExchangeAbstraction.sol
pragma solidity ^0.6.0;
library SushiswapExchangeAbstraction
{
function _calcConversionOutputFromInput(address _from, address _to, uint256 _inputAmount) internal view returns (uint256 _outputAmount)
{
address _router = $.Sushiswap_ROUTER02;
address _WETH = Router02(_router).WETH();
address[] memory _path = _buildPath(_from, _WETH, _to);
return Router02(_router).getAmountsOut(_inputAmount, _path)[_path.length - 1];
}
function _calcConversionInputFromOutput(address _from, address _to, uint256 _outputAmount) internal view returns (uint256 _inputAmount)
{
address _router = $.Sushiswap_ROUTER02;
address _WETH = Router02(_router).WETH();
address[] memory _path = _buildPath(_from, _WETH, _to);
return Router02(_router).getAmountsIn(_outputAmount, _path)[0];
}
function _convertFunds(address _from, address _to, uint256 _inputAmount, uint256 _minOutputAmount) internal returns (uint256 _outputAmount)
{
address _router = $.Sushiswap_ROUTER02;
address _WETH = Router02(_router).WETH();
address[] memory _path = _buildPath(_from, _WETH, _to);
Transfers._approveFunds(_from, _router, _inputAmount);
return Router02(_router).swapExactTokensForTokens(_inputAmount, _minOutputAmount, _path, address(this), uint256(-1))[_path.length - 1];
}
function _buildPath(address _from, address _WETH, address _to) internal pure returns (address[] memory _path)
{
if (_from == _WETH || _to == _WETH) {
_path = new address[](2);
_path[0] = _from;
_path[1] = _to;
return _path;
} else {
_path = new address[](3);
_path[0] = _from;
_path[1] = _WETH;
_path[2] = _to;
return _path;
}
}
}
// File: contracts/GExchange.sol
pragma solidity ^0.6.0;
/**
* @dev Custom and uniform interface to a decentralized exchange. It is used
* to estimate and convert funds whenever necessary. This furnishes
* client contracts with the flexibility to replace conversion strategy
* and routing, dynamically, by delegating these operations to different
* external contracts that share this common interface. See
* GUniswapV2Exchange.sol for further documentation.
*/
interface GExchange
{
// view functions
function calcConversionOutputFromInput(address _from, address _to, uint256 _inputAmount) external view returns (uint256 _outputAmount);
function calcConversionInputFromOutput(address _from, address _to, uint256 _outputAmount) external view returns (uint256 _inputAmount);
// open functions
function convertFunds(address _from, address _to, uint256 _inputAmount, uint256 _minOutputAmount) external returns (uint256 _outputAmount);
}
// File: contracts/modules/Conversions.sol
pragma solidity ^0.6.0;
library Conversions
{
function _dynamicConvertFunds(address _exchange, address _from, address _to, uint256 _inputAmount, uint256 _minOutputAmount) internal returns (uint256 _outputAmount)
{
Transfers._approveFunds(_from, _exchange, _inputAmount);
try GExchange(_exchange).convertFunds(_from, _to, _inputAmount, _minOutputAmount) returns (uint256 _outAmount) {
return _outAmount;
} catch (bytes memory /* _data */) {
Transfers._approveFunds(_from, _exchange, 0);
return 0;
}
}
}
// File: contracts/modules/AaveFlashLoanAbstraction.sol
pragma solidity ^0.6.0;
library AaveFlashLoanAbstraction
{
using SafeMath for uint256;
uint256 constant FLASH_LOAN_FEE_RATIO = 9e14; // 0.09%
function _estimateFlashLoanFee(address /* _token */, uint256 _netAmount) internal pure returns (uint256 _feeAmount)
{
return _netAmount.mul(FLASH_LOAN_FEE_RATIO).div(1e18);
}
function _getFlashLoanLiquidity(address _token) internal view returns (uint256 _liquidityAmount)
{
address _pool = $.Aave_AAVE_LENDING_POOL;
// this is the code in solidity, but does not compile
// try LendingPool(_pool).getReserveData(_token) returns (uint256 _totalLiquidity, uint256 _availableLiquidity, uint256 _totalBorrowsStable, uint256 _totalBorrowsVariable, uint256 _liquidityRate, uint256 _variableBorrowRate, uint256 _stableBorrowRate, uint256 _averageStableBorrowRate, uint256 _utilizationRate, uint256 _liquidityIndex, uint256 _variableBorrowIndex, address _aTokenAddress, uint40 _lastUpdateTimestamp) {
// return _availableLiquidity;
// } catch (bytes memory /* _data */) {
// return 0;
// }
// we use EVM assembly instead
bytes memory _data = abi.encodeWithSignature("getReserveData(address)", _token);
uint256[2] memory _result;
assembly {
let _success := staticcall(gas(), _pool, add(_data, 32), mload(_data), _result, 64)
if iszero(_success) {
mstore(add(_result, 32), 0)
}
}
return _result[1];
}
function _requestFlashLoan(address _token, uint256 _netAmount, bytes memory _context) internal returns (bool _success)
{
address _pool = $.Aave_AAVE_LENDING_POOL;
try LendingPool(_pool).flashLoan(address(this), _token, _netAmount, _context) {
return true;
} catch (bytes memory /* _data */) {
return false;
}
}
function _paybackFlashLoan(address _token, uint256 _grossAmount) internal
{
address _poolCore = $.Aave_AAVE_LENDING_POOL_CORE;
Transfers._pushFunds(_token, _poolCore, _grossAmount);
}
}
// File: contracts/modules/DydxFlashLoanAbstraction.sol
pragma solidity ^0.6.0;
library DydxFlashLoanAbstraction
{
using SafeMath for uint256;
function _estimateFlashLoanFee(address /* _token */, uint256 /* _netAmount */) internal pure returns (uint256 _feeAmount)
{
return 2;
}
function _getFlashLoanLiquidity(address _token) internal view returns (uint256 _liquidityAmount)
{
address _solo = $.Dydx_SOLO_MARGIN;
return IERC20(_token).balanceOf(_solo);
}
function _requestFlashLoan(address _token, uint256 _netAmount, bytes memory _context) internal returns (bool _success)
{
address _solo = $.Dydx_SOLO_MARGIN;
uint256 _feeAmount = 2;
uint256 _grossAmount = _netAmount.add(_feeAmount);
uint256 _marketId = uint256(-1);
uint256 _numMarkets = SoloMargin(_solo).getNumMarkets();
for (uint256 _i = 0; _i < _numMarkets; _i++) {
address _address = SoloMargin(_solo).getMarketTokenAddress(_i);
if (_address == _token) {
_marketId = _i;
break;
}
}
if (_marketId == uint256(-1)) return false;
Account.Info[] memory _accounts = new Account.Info[](1);
_accounts[0] = Account.Info({ owner: address(this), number: 1 });
Actions.ActionArgs[] memory _actions = new Actions.ActionArgs[](3);
_actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _netAmount
}),
primaryMarketId: _marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
_actions[1] = Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: abi.encode(_token, _netAmount, _feeAmount, _context)
});
_actions[2] = Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _grossAmount
}),
primaryMarketId: _marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
try SoloMargin(_solo).operate(_accounts, _actions) {
return true;
} catch (bytes memory /* _data */) {
return false;
}
}
function _paybackFlashLoan(address _token, uint256 _grossAmount) internal
{
address _solo = $.Dydx_SOLO_MARGIN;
Transfers._approveFunds(_token, _solo, _grossAmount);
}
}
// File: contracts/modules/FlashLoans.sol
pragma solidity ^0.6.0;
library FlashLoans
{
enum Provider { Aave, Dydx }
function _estimateFlashLoanFee(Provider _provider, address _token, uint256 _netAmount) internal pure returns (uint256 _feeAmount)
{
if (_provider == Provider.Aave) return AaveFlashLoanAbstraction._estimateFlashLoanFee(_token, _netAmount);
if (_provider == Provider.Dydx) return DydxFlashLoanAbstraction._estimateFlashLoanFee(_token, _netAmount);
}
function _getFlashLoanLiquidity(address _token) internal view returns (uint256 _liquidityAmount)
{
uint256 _liquidityAmountDydx = DydxFlashLoanAbstraction._getFlashLoanLiquidity(_token);
uint256 _liquidityAmountAave = AaveFlashLoanAbstraction._getFlashLoanLiquidity(_token);
return Math._max(_liquidityAmountDydx, _liquidityAmountAave);
}
function _requestFlashLoan(address _token, uint256 _netAmount, bytes memory _context) internal returns (bool _success)
{
_success = DydxFlashLoanAbstraction._requestFlashLoan(_token, _netAmount, _context);
if (_success) return true;
_success = AaveFlashLoanAbstraction._requestFlashLoan(_token, _netAmount, _context);
if (_success) return true;
return false;
}
function _paybackFlashLoan(Provider _provider, address _token, uint256 _grossAmount) internal
{
if (_provider == Provider.Aave) return AaveFlashLoanAbstraction._paybackFlashLoan(_token, _grossAmount);
if (_provider == Provider.Dydx) return DydxFlashLoanAbstraction._paybackFlashLoan(_token, _grossAmount);
}
}
// File: contracts/modules/BalancerLiquidityPoolAbstraction.sol
pragma solidity ^0.6.0;
library BalancerLiquidityPoolAbstraction
{
using SafeMath for uint256;
uint256 constant MIN_AMOUNT = 1e6;
uint256 constant TOKEN0_WEIGHT = 25e18; // 25/50 = 50%
uint256 constant TOKEN1_WEIGHT = 25e18; // 25/50 = 50%
uint256 constant SWAP_FEE = 10e16; // 10%
function _createPool(address _token0, uint256 _amount0, address _token1, uint256 _amount1) internal returns (address _pool)
{
require(_amount0 >= MIN_AMOUNT && _amount1 >= MIN_AMOUNT, "amount below the minimum");
_pool = BFactory($.Balancer_FACTORY).newBPool();
Transfers._approveFunds(_token0, _pool, _amount0);
Transfers._approveFunds(_token1, _pool, _amount1);
BPool(_pool).bind(_token0, _amount0, TOKEN0_WEIGHT);
BPool(_pool).bind(_token1, _amount1, TOKEN1_WEIGHT);
BPool(_pool).setSwapFee(SWAP_FEE);
BPool(_pool).finalize();
return _pool;
}
function _joinPool(address _pool, address _token, uint256 _maxAmount) internal returns (uint256 _amount)
{
uint256 _balanceAmount = BPool(_pool).getBalance(_token);
if (_balanceAmount == 0) return 0;
uint256 _limitAmount = _balanceAmount.div(2);
_amount = Math._min(_maxAmount, _limitAmount);
Transfers._approveFunds(_token, _pool, _amount);
BPool(_pool).joinswapExternAmountIn(_token, _amount, 0);
return _amount;
}
function _exitPool(address _pool, uint256 _percent) internal returns (uint256 _amount0, uint256 _amount1)
{
if (_percent == 0) return (0, 0);
address[] memory _tokens = BPool(_pool).getFinalTokens();
_amount0 = Transfers._getBalance(_tokens[0]);
_amount1 = Transfers._getBalance(_tokens[1]);
uint256 _poolAmount = Transfers._getBalance(_pool);
uint256 _poolExitAmount = _poolAmount.mul(_percent).div(1e18);
uint256[] memory _minAmountsOut = new uint256[](2);
_minAmountsOut[0] = 0;
_minAmountsOut[1] = 0;
BPool(_pool).exitPool(_poolExitAmount, _minAmountsOut);
_amount0 = Transfers._getBalance(_tokens[0]).sub(_amount0);
_amount1 = Transfers._getBalance(_tokens[1]).sub(_amount1);
return (_amount0, _amount1);
}
}
// File: contracts/modules/CompoundLendingMarketAbstraction.sol
pragma solidity ^0.6.0;
library CompoundLendingMarketAbstraction
{
using SafeMath for uint256;
function _getUnderlyingToken(address _ctoken) internal view returns (address _token)
{
if (_ctoken == $.cETH) return $.WETH;
return CToken(_ctoken).underlying();
}
function _getCollateralRatio(address _ctoken) internal view returns (uint256 _collateralFactor)
{
address _comptroller = $.Compound_COMPTROLLER;
(, _collateralFactor) = Comptroller(_comptroller).markets(_ctoken);
return _collateralFactor;
}
function _getMarketAmount(address _ctoken) internal view returns (uint256 _marketAmount)
{
return CToken(_ctoken).getCash();
}
function _getLiquidityAmount(address _ctoken) internal view returns (uint256 _liquidityAmount)
{
address _comptroller = $.Compound_COMPTROLLER;
(uint256 _result, uint256 _liquidity, uint256 _shortfall) = Comptroller(_comptroller).getAccountLiquidity(address(this));
if (_result != 0) return 0;
if (_shortfall > 0) return 0;
address _priceOracle = Comptroller(_comptroller).oracle();
uint256 _price = PriceOracle(_priceOracle).getUnderlyingPrice(_ctoken);
return _liquidity.mul(1e18).div(_price);
}
function _getAvailableAmount(address _ctoken, uint256 _marginAmount) internal view returns (uint256 _availableAmount)
{
uint256 _liquidityAmount = _getLiquidityAmount(_ctoken);
if (_liquidityAmount <= _marginAmount) return 0;
return Math._min(_liquidityAmount.sub(_marginAmount), _getMarketAmount(_ctoken));
}
function _getExchangeRate(address _ctoken) internal view returns (uint256 _exchangeRate)
{
return CToken(_ctoken).exchangeRateStored();
}
function _fetchExchangeRate(address _ctoken) internal returns (uint256 _exchangeRate)
{
return CToken(_ctoken).exchangeRateCurrent();
}
function _getLendAmount(address _ctoken) internal view returns (uint256 _amount)
{
return CToken(_ctoken).balanceOf(address(this)).mul(_getExchangeRate(_ctoken)).div(1e18);
}
function _fetchLendAmount(address _ctoken) internal returns (uint256 _amount)
{
return CToken(_ctoken).balanceOfUnderlying(address(this));
}
function _getBorrowAmount(address _ctoken) internal view returns (uint256 _amount)
{
return CToken(_ctoken).borrowBalanceStored(address(this));
}
function _fetchBorrowAmount(address _ctoken) internal returns (uint256 _amount)
{
return CToken(_ctoken).borrowBalanceCurrent(address(this));
}
function _enter(address _ctoken) internal returns (bool _success)
{
address _comptroller = $.Compound_COMPTROLLER;
address[] memory _ctokens = new address[](1);
_ctokens[0] = _ctoken;
try Comptroller(_comptroller).enterMarkets(_ctokens) returns (uint256[] memory _errorCodes) {
return _errorCodes[0] == 0;
} catch (bytes memory /* _data */) {
return false;
}
}
function _lend(address _ctoken, uint256 _amount) internal returns (bool _success)
{
if (_ctoken == $.cETH) {
if (!Wrapping._unwrap(_amount)) return false;
try CToken(_ctoken).mint{value: _amount}() {
return true;
} catch (bytes memory /* _data */) {
assert(Wrapping._wrap(_amount));
return false;
}
} else {
address _token = _getUnderlyingToken(_ctoken);
Transfers._approveFunds(_token, _ctoken, _amount);
try CToken(_ctoken).mint(_amount) returns (uint256 _errorCode) {
return _errorCode == 0;
} catch (bytes memory /* _data */) {
return false;
}
}
}
function _redeem(address _ctoken, uint256 _amount) internal returns (bool _success)
{
if (_ctoken == $.cETH) {
try CToken(_ctoken).redeemUnderlying(_amount) returns (uint256 _errorCode) {
if (_errorCode == 0) {
assert(Wrapping._wrap(_amount));
return true;
} else {
return false;
}
} catch (bytes memory /* _data */) {
return false;
}
} else {
try CToken(_ctoken).redeemUnderlying(_amount) returns (uint256 _errorCode) {
return _errorCode == 0;
} catch (bytes memory /* _data */) {
return false;
}
}
}
function _borrow(address _ctoken, uint256 _amount) internal returns (bool _success)
{
if (_ctoken == $.cETH) {
try CToken(_ctoken).borrow(_amount) returns (uint256 _errorCode) {
if (_errorCode == 0) {
assert(Wrapping._wrap(_amount));
return true;
} else {
return false;
}
} catch (bytes memory /* _data */) {
return false;
}
} else {
try CToken(_ctoken).borrow(_amount) returns (uint256 _errorCode) {
return _errorCode == 0;
} catch (bytes memory /* _data */) {
return false;
}
}
}
function _repay(address _ctoken, uint256 _amount) internal returns (bool _success)
{
if (_ctoken == $.cETH) {
if (!Wrapping._unwrap(_amount)) return false;
try CToken(_ctoken).repayBorrow{value: _amount}() {
return true;
} catch (bytes memory /* _data */) {
assert(Wrapping._wrap(_amount));
return false;
}
} else {
address _token = _getUnderlyingToken(_ctoken);
Transfers._approveFunds(_token, _ctoken, _amount);
try CToken(_ctoken).repayBorrow(_amount) returns (uint256 _errorCode) {
return _errorCode == 0;
} catch (bytes memory /* _data */) {
return false;
}
}
}
function _safeEnter(address _ctoken) internal
{
require(_enter(_ctoken), "enter failed");
}
function _safeLend(address _ctoken, uint256 _amount) internal
{
require(_lend(_ctoken, _amount), "lend failure");
}
function _safeRedeem(address _ctoken, uint256 _amount) internal
{
require(_redeem(_ctoken, _amount), "redeem failure");
}
function _safeBorrow(address _ctoken, uint256 _amount) internal
{
require(_borrow(_ctoken, _amount), "borrow failure");
}
function _safeRepay(address _ctoken, uint256 _amount) internal
{
require(_repay(_ctoken, _amount), "repay failure");
}
}
// File: contracts/G.sol
pragma solidity ^0.6.0;
/**
* @dev This public library provides a single entrypoint to all the relevant
* internal libraries available in the modules folder. It exists to
* circunvent the contract size limitation imposed by the EVM. All function
* calls are directly delegated to the target library function preserving
* argument and return values exactly as they are. Thit library is shared
* by all contracts and even other public libraries from this repository,
* therefore it needs to be published alongside them.
*/
library G
{
function min(uint256 _amount1, uint256 _amount2) public pure returns (uint256 _minAmount) { return Math._min(_amount1, _amount2); }
function safeWrap(uint256 _amount) public { Wrapping._safeWrap(_amount); }
function safeUnwrap(uint256 _amount) public { Wrapping._safeUnwrap(_amount); }
function getBalance(address _token) public view returns (uint256 _balance) { return Transfers._getBalance(_token); }
function pullFunds(address _token, address _from, uint256 _amount) public { Transfers._pullFunds(_token, _from, _amount); }
function pushFunds(address _token, address _to, uint256 _amount) public { Transfers._pushFunds(_token, _to, _amount); }
function approveFunds(address _token, address _to, uint256 _amount) public { Transfers._approveFunds(_token, _to, _amount); }
function dynamicConvertFunds(address _exchange, address _from, address _to, uint256 _inputAmount, uint256 _minOutputAmount) public returns (uint256 _outputAmount) { return Conversions._dynamicConvertFunds(_exchange, _from, _to, _inputAmount, _minOutputAmount); }
function getFlashLoanLiquidity(address _token) public view returns (uint256 _liquidityAmount) { return FlashLoans._getFlashLoanLiquidity(_token); }
function requestFlashLoan(address _token, uint256 _amount, bytes memory _context) public returns (bool _success) { return FlashLoans._requestFlashLoan(_token, _amount, _context); }
function paybackFlashLoan(FlashLoans.Provider _provider, address _token, uint256 _grossAmount) public { FlashLoans._paybackFlashLoan(_provider, _token, _grossAmount); }
function createPool(address _token0, uint256 _amount0, address _token1, uint256 _amount1) public returns (address _pool) { return BalancerLiquidityPoolAbstraction._createPool(_token0, _amount0, _token1, _amount1); }
function joinPool(address _pool, address _token, uint256 _maxAmount) public returns (uint256 _amount) { return BalancerLiquidityPoolAbstraction._joinPool(_pool, _token, _maxAmount); }
function exitPool(address _pool, uint256 _percent) public returns (uint256 _amount0, uint256 _amount1) { return BalancerLiquidityPoolAbstraction._exitPool(_pool, _percent); }
function getUnderlyingToken(address _ctoken) public view returns (address _token) { return CompoundLendingMarketAbstraction._getUnderlyingToken(_ctoken); }
function getCollateralRatio(address _ctoken) public view returns (uint256 _collateralFactor) { return CompoundLendingMarketAbstraction._getCollateralRatio(_ctoken); }
function getLiquidityAmount(address _ctoken) public view returns (uint256 _liquidityAmount) { return CompoundLendingMarketAbstraction._getLiquidityAmount(_ctoken); }
function getExchangeRate(address _ctoken) public view returns (uint256 _exchangeRate) { return CompoundLendingMarketAbstraction._getExchangeRate(_ctoken); }
function fetchExchangeRate(address _ctoken) public returns (uint256 _exchangeRate) { return CompoundLendingMarketAbstraction._fetchExchangeRate(_ctoken); }
function getLendAmount(address _ctoken) public view returns (uint256 _amount) { return CompoundLendingMarketAbstraction._getLendAmount(_ctoken); }
function fetchLendAmount(address _ctoken) public returns (uint256 _amount) { return CompoundLendingMarketAbstraction._fetchLendAmount(_ctoken); }
function getBorrowAmount(address _ctoken) public view returns (uint256 _amount) { return CompoundLendingMarketAbstraction._getBorrowAmount(_ctoken); }
function fetchBorrowAmount(address _ctoken) public returns (uint256 _amount) { return CompoundLendingMarketAbstraction._fetchBorrowAmount(_ctoken); }
function lend(address _ctoken, uint256 _amount) public returns (bool _success) { return CompoundLendingMarketAbstraction._lend(_ctoken, _amount); }
function redeem(address _ctoken, uint256 _amount) public returns (bool _success) { return CompoundLendingMarketAbstraction._redeem(_ctoken, _amount); }
function borrow(address _ctoken, uint256 _amount) public returns (bool _success) { return CompoundLendingMarketAbstraction._borrow(_ctoken, _amount); }
function repay(address _ctoken, uint256 _amount) public returns (bool _success) { return CompoundLendingMarketAbstraction._repay(_ctoken, _amount); }
function safeLend(address _ctoken, uint256 _amount) public { CompoundLendingMarketAbstraction._safeLend(_ctoken, _amount); }
function safeRedeem(address _ctoken, uint256 _amount) public { CompoundLendingMarketAbstraction._safeRedeem(_ctoken, _amount); }
}
// File: contracts/GToken.sol
pragma solidity ^0.6.0;
/**
* @dev Complete top-level interface for gTokens, implemented by the
* GTokenBase contract. See GTokenBase.sol for further documentation.
*/
interface GToken is IERC20
{
// pure functions
function calcDepositSharesFromCost(uint256 _cost, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee) external pure returns (uint256 _netShares, uint256 _feeShares);
function calcDepositCostFromShares(uint256 _netShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee) external pure returns (uint256 _cost, uint256 _feeShares);
function calcWithdrawalSharesFromCost(uint256 _cost, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee) external pure returns (uint256 _grossShares, uint256 _feeShares);
function calcWithdrawalCostFromShares(uint256 _grossShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee) external pure returns (uint256 _cost, uint256 _feeShares);
// view functions
function stakesToken() external view returns (address _stakesToken);
function reserveToken() external view returns (address _reserveToken);
function totalReserve() external view returns (uint256 _totalReserve);
function depositFee() external view returns (uint256 _depositFee);
function withdrawalFee() external view returns (uint256 _withdrawalFee);
function liquidityPool() external view returns (address _liquidityPool);
function liquidityPoolBurningRate() external view returns (uint256 _burningRate);
function liquidityPoolLastBurningTime() external view returns (uint256 _lastBurningTime);
function liquidityPoolMigrationRecipient() external view returns (address _migrationRecipient);
function liquidityPoolMigrationUnlockTime() external view returns (uint256 _migrationUnlockTime);
// open functions
function deposit(uint256 _cost) external;
function withdraw(uint256 _grossShares) external;
// priviledged functions
function allocateLiquidityPool(uint256 _stakesAmount, uint256 _sharesAmount) external;
function setLiquidityPoolBurningRate(uint256 _burningRate) external;
function burnLiquidityPoolPortion() external;
function initiateLiquidityPoolMigration(address _migrationRecipient) external;
function cancelLiquidityPoolMigration() external;
function completeLiquidityPoolMigration() external;
// emitted events
event BurnLiquidityPoolPortion(uint256 _stakesAmount, uint256 _sharesAmount);
event InitiateLiquidityPoolMigration(address indexed _migrationRecipient);
event CancelLiquidityPoolMigration(address indexed _migrationRecipient);
event CompleteLiquidityPoolMigration(address indexed _migrationRecipient, uint256 _stakesAmount, uint256 _sharesAmount);
}
// File: contracts/GCToken.sol
pragma solidity ^0.6.0;
/**
* @dev Complete top-level interface for gcTokens, implemented by the
* GCTokenBase contract. See GCTokenBase.sol for further documentation.
*/
interface GCToken is GToken
{
// pure functions
function calcCostFromUnderlyingCost(uint256 _underlyingCost, uint256 _exchangeRate) external pure returns (uint256 _cost);
function calcUnderlyingCostFromCost(uint256 _cost, uint256 _exchangeRate) external pure returns (uint256 _underlyingCost);
function calcDepositSharesFromUnderlyingCost(uint256 _underlyingCost, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee, uint256 _exchangeRate) external pure returns (uint256 _netShares, uint256 _feeShares);
function calcDepositUnderlyingCostFromShares(uint256 _netShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee, uint256 _exchangeRate) external pure returns (uint256 _underlyingCost, uint256 _feeShares);
function calcWithdrawalSharesFromUnderlyingCost(uint256 _underlyingCost, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee, uint256 _exchangeRate) external pure returns (uint256 _grossShares, uint256 _feeShares);
function calcWithdrawalUnderlyingCostFromShares(uint256 _grossShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee, uint256 _exchangeRate) external pure returns (uint256 _underlyingCost, uint256 _feeShares);
// view functions
function miningToken() external view returns (address _miningToken);
function growthToken() external view returns (address _growthToken);
function underlyingToken() external view returns (address _underlyingToken);
function exchangeRate() external view returns (uint256 _exchangeRate);
function totalReserveUnderlying() external view returns (uint256 _totalReserveUnderlying);
function lendingReserveUnderlying() external view returns (uint256 _lendingReserveUnderlying);
function borrowingReserveUnderlying() external view returns (uint256 _borrowingReserveUnderlying);
function exchange() external view returns (address _exchange);
function miningGulpRange() external view returns (uint256 _miningMinGulpAmount, uint256 _miningMaxGulpAmount);
function growthGulpRange() external view returns (uint256 _growthMinGulpAmount, uint256 _growthMaxGulpAmount);
function collateralizationRatio() external view returns (uint256 _collateralizationRatio, uint256 _collateralizationMargin);
// open functions
function depositUnderlying(uint256 _underlyingCost) external;
function withdrawUnderlying(uint256 _grossShares) external;
// priviledged functions
function setExchange(address _exchange) external;
function setMiningGulpRange(uint256 _miningMinGulpAmount, uint256 _miningMaxGulpAmount) external;
function setGrowthGulpRange(uint256 _growthMinGulpAmount, uint256 _growthMaxGulpAmount) external;
function setCollateralizationRatio(uint256 _collateralizationRatio, uint256 _collateralizationMargin) external;
}
// File: contracts/GFormulae.sol
pragma solidity ^0.6.0;
/**
* @dev Pure implementation of deposit/minting and withdrawal/burning formulas
* for gTokens.
* All operations assume that, if total supply is 0, then the total
* reserve is also 0, and vice-versa.
* Fees are calculated percentually based on the gross amount.
* See GTokenBase.sol for further documentation.
*/
library GFormulae
{
using SafeMath for uint256;
/* deposit(cost):
* price = reserve / supply
* gross = cost / price
* net = gross * 0.99 # fee is assumed to be 1% for simplicity
* fee = gross - net
* return net, fee
*/
function _calcDepositSharesFromCost(uint256 _cost, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee) internal pure returns (uint256 _netShares, uint256 _feeShares)
{
uint256 _grossShares = _totalSupply == _totalReserve ? _cost : _cost.mul(_totalSupply).div(_totalReserve);
_netShares = _grossShares.mul(uint256(1e18).sub(_depositFee)).div(1e18);
_feeShares = _grossShares.sub(_netShares);
return (_netShares, _feeShares);
}
/* deposit_reverse(net):
* price = reserve / supply
* gross = net / 0.99 # fee is assumed to be 1% for simplicity
* cost = gross * price
* fee = gross - net
* return cost, fee
*/
function _calcDepositCostFromShares(uint256 _netShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee) internal pure returns (uint256 _cost, uint256 _feeShares)
{
uint256 _grossShares = _netShares.mul(1e18).div(uint256(1e18).sub(_depositFee));
_cost = _totalReserve == _totalSupply ? _grossShares : _grossShares.mul(_totalReserve).div(_totalSupply);
_feeShares = _grossShares.sub(_netShares);
return (_cost, _feeShares);
}
/* withdrawal_reverse(cost):
* price = reserve / supply
* net = cost / price
* gross = net / 0.99 # fee is assumed to be 1% for simplicity
* fee = gross - net
* return gross, fee
*/
function _calcWithdrawalSharesFromCost(uint256 _cost, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee) internal pure returns (uint256 _grossShares, uint256 _feeShares)
{
uint256 _netShares = _cost == _totalReserve ? _totalSupply : _cost.mul(_totalSupply).div(_totalReserve);
_grossShares = _netShares.mul(1e18).div(uint256(1e18).sub(_withdrawalFee));
_feeShares = _grossShares.sub(_netShares);
return (_grossShares, _feeShares);
}
/* withdrawal(gross):
* price = reserve / supply
* net = gross * 0.99 # fee is assumed to be 1% for simplicity
* cost = net * price
* fee = gross - net
* return cost, fee
*/
function _calcWithdrawalCostFromShares(uint256 _grossShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee) internal pure returns (uint256 _cost, uint256 _feeShares)
{
uint256 _netShares = _grossShares.mul(uint256(1e18).sub(_withdrawalFee)).div(1e18);
_cost = _netShares == _totalSupply ? _totalReserve : _netShares.mul(_totalReserve).div(_totalSupply);
_feeShares = _grossShares.sub(_netShares);
return (_cost, _feeShares);
}
}
// File: contracts/GCFormulae.sol
pragma solidity ^0.6.0;
/**
* @dev Pure implementation of deposit/minting and withdrawal/burning formulas
* for gTokens calculated based on the cToken underlying asset
* (e.g. DAI for cDAI). See GFormulae.sol and GCTokenBase.sol for further
* documentation.
*/
library GCFormulae
{
using SafeMath for uint256;
/**
* @dev Simple token to cToken formula from Compound
*/
function _calcCostFromUnderlyingCost(uint256 _underlyingCost, uint256 _exchangeRate) internal pure returns (uint256 _cost)
{
return _underlyingCost.mul(1e18).div(_exchangeRate);
}
/**
* @dev Simple cToken to token formula from Compound
*/
function _calcUnderlyingCostFromCost(uint256 _cost, uint256 _exchangeRate) internal pure returns (uint256 _underlyingCost)
{
return _cost.mul(_exchangeRate).div(1e18);
}
/**
* @dev Composition of the gToken deposit formula with the Compound
* conversion formula to obtain the gcToken deposit formula in
* terms of the cToken underlying asset.
*/
function _calcDepositSharesFromUnderlyingCost(uint256 _underlyingCost, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee, uint256 _exchangeRate) internal pure returns (uint256 _netShares, uint256 _feeShares)
{
uint256 _cost = _calcCostFromUnderlyingCost(_underlyingCost, _exchangeRate);
return GFormulae._calcDepositSharesFromCost(_cost, _totalReserve, _totalSupply, _depositFee);
}
/**
* @dev Composition of the gToken reserve deposit formula with the
* Compound conversion formula to obtain the gcToken reverse
* deposit formula in terms of the cToken underlying asset.
*/
function _calcDepositUnderlyingCostFromShares(uint256 _netShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee, uint256 _exchangeRate) internal pure returns (uint256 _underlyingCost, uint256 _feeShares)
{
uint256 _cost;
(_cost, _feeShares) = GFormulae._calcDepositCostFromShares(_netShares, _totalReserve, _totalSupply, _depositFee);
return (_calcUnderlyingCostFromCost(_cost, _exchangeRate), _feeShares);
}
/**
* @dev Composition of the gToken reserve withdrawal formula with the
* Compound conversion formula to obtain the gcToken reverse
* withdrawal formula in terms of the cToken underlying asset.
*/
function _calcWithdrawalSharesFromUnderlyingCost(uint256 _underlyingCost, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee, uint256 _exchangeRate) internal pure returns (uint256 _grossShares, uint256 _feeShares)
{
uint256 _cost = _calcCostFromUnderlyingCost(_underlyingCost, _exchangeRate);
return GFormulae._calcWithdrawalSharesFromCost(_cost, _totalReserve, _totalSupply, _withdrawalFee);
}
/**
* @dev Composition of the gToken withdrawal formula with the Compound
* conversion formula to obtain the gcToken withdrawal formula in
* terms of the cToken underlying asset.
*/
function _calcWithdrawalUnderlyingCostFromShares(uint256 _grossShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee, uint256 _exchangeRate) internal pure returns (uint256 _underlyingCost, uint256 _feeShares)
{
uint256 _cost;
(_cost, _feeShares) = GFormulae._calcWithdrawalCostFromShares(_grossShares, _totalReserve, _totalSupply, _withdrawalFee);
return (_calcUnderlyingCostFromCost(_cost, _exchangeRate), _feeShares);
}
}
// File: contracts/GLiquidityPoolManager.sol
pragma solidity ^0.6.0;
/**
* @dev This library implements data structure abstraction for the liquidity
* pool management code in order to circuvent the EVM contract size limit.
* It is therefore a public library shared by all gToken contracts and
* needs to be published alongside them. See GTokenBase.sol for further
* documentation.
*/
library GLiquidityPoolManager
{
using GLiquidityPoolManager for GLiquidityPoolManager.Self;
uint256 constant MAXIMUM_BURNING_RATE = 2e16; // 2%
uint256 constant DEFAULT_BURNING_RATE = 5e15; // 0.5%
uint256 constant BURNING_INTERVAL = 7 days;
uint256 constant MIGRATION_INTERVAL = 7 days;
enum State { Created, Allocated, Migrating, Migrated }
struct Self {
address stakesToken;
address sharesToken;
State state;
address liquidityPool;
uint256 burningRate;
uint256 lastBurningTime;
address migrationRecipient;
uint256 migrationUnlockTime;
}
/**
* @dev Initializes the data structure. This method is exposed publicly.
* @param _stakesToken The ERC-20 token address to be used as stakes
* token (GRO).
* @param _sharesToken The ERC-20 token address to be used as shares
* token (gToken).
*/
function init(Self storage _self, address _stakesToken, address _sharesToken) public
{
_self.stakesToken = _stakesToken;
_self.sharesToken = _sharesToken;
_self.state = State.Created;
_self.liquidityPool = address(0);
_self.burningRate = DEFAULT_BURNING_RATE;
_self.lastBurningTime = 0;
_self.migrationRecipient = address(0);
_self.migrationUnlockTime = uint256(-1);
}
/**
* @dev Verifies whether or not a liquidity pool is migrating or
* has migrated. This method is exposed publicly.
* @return _hasMigrated A boolean indicating whether or not the pool
* migration has started.
*/
function hasMigrated(Self storage _self) public view returns (bool _hasMigrated)
{
return _self.state == State.Migrating || _self.state == State.Migrated;
}
/**
* @dev Moves the current balances (if any) of stakes and shares tokens
* to the liquidity pool. This method is exposed publicly.
*/
function gulpPoolAssets(Self storage _self) public
{
if (!_self._hasPool()) return;
G.joinPool(_self.liquidityPool, _self.stakesToken, G.getBalance(_self.stakesToken));
G.joinPool(_self.liquidityPool, _self.sharesToken, G.getBalance(_self.sharesToken));
}
/**
* @dev Sets the liquidity pool burning rate. This method is exposed
* publicly.
* @param _burningRate The percent value of the liquidity pool to be
* burned at each 7-day period.
*/
function setBurningRate(Self storage _self, uint256 _burningRate) public
{
require(_burningRate <= MAXIMUM_BURNING_RATE, "invalid rate");
_self.burningRate = _burningRate;
}
/**
* @dev Burns a portion of the liquidity pool according to the defined
* burning rate. It must happen at most once every 7-days. This
* method does not actually burn the funds, but it will redeem
* the amounts from the pool to the caller contract, which is then
* assumed to perform the burn. This method is exposed publicly.
* @return _stakesAmount The amount of stakes (GRO) redeemed from the pool.
* @return _sharesAmount The amount of shares (gToken) redeemed from the pool.
*/
function burnPoolPortion(Self storage _self) public returns (uint256 _stakesAmount, uint256 _sharesAmount)
{
require(_self._hasPool(), "pool not available");
require(now >= _self.lastBurningTime + BURNING_INTERVAL, "must wait lock interval");
_self.lastBurningTime = now;
return G.exitPool(_self.liquidityPool, _self.burningRate);
}
/**
* @dev Creates a fresh new liquidity pool and deposits the initial
* amounts of the stakes token and the shares token. The pool
* if configure 50%/50% with a 10% swap fee. This method is exposed
* publicly.
* @param _stakesAmount The amount of stakes token initially deposited
* into the pool.
* @param _sharesAmount The amount of shares token initially deposited
* into the pool.
*/
function allocatePool(Self storage _self, uint256 _stakesAmount, uint256 _sharesAmount) public
{
require(_self.state == State.Created, "pool cannot be allocated");
_self.state = State.Allocated;
_self.liquidityPool = G.createPool(_self.stakesToken, _stakesAmount, _self.sharesToken, _sharesAmount);
}
/**
* @dev Initiates the liquidity pool migration by setting a funds
* recipent and starting the clock towards the 7-day grace period.
* This method is exposed publicly.
* @param _migrationRecipient The recipient address to where funds will
* be transfered.
*/
function initiatePoolMigration(Self storage _self, address _migrationRecipient) public
{
require(_self.state == State.Allocated || _self.state == State.Migrated, "migration unavailable");
_self.state = State.Migrating;
_self.migrationRecipient = _migrationRecipient;
_self.migrationUnlockTime = now + MIGRATION_INTERVAL;
}
/**
* @dev Cancels the liquidity pool migration by reseting the procedure
* to its original state. This method is exposed publicly.
* @return _migrationRecipient The address of the former recipient.
*/
function cancelPoolMigration(Self storage _self) public returns (address _migrationRecipient)
{
require(_self.state == State.Migrating, "migration not initiated");
_migrationRecipient = _self.migrationRecipient;
_self.state = State.Allocated;
_self.migrationRecipient = address(0);
_self.migrationUnlockTime = uint256(-1);
return _migrationRecipient;
}
/**
* @dev Completes the liquidity pool migration by redeeming all funds
* from the pool. This method does not actually transfer the
* redemeed funds to the recipient, it assumes the caller contract
* will perform that. This method is exposed publicly.
* @return _migrationRecipient The address of the recipient.
* @return _stakesAmount The amount of stakes (GRO) redeemed from the pool.
* @return _sharesAmount The amount of shares (gToken) redeemed from the pool.
*/
function completePoolMigration(Self storage _self) public returns (address _migrationRecipient, uint256 _stakesAmount, uint256 _sharesAmount)
{
require(_self.state == State.Migrating, "migration not initiated");
require(now >= _self.migrationUnlockTime, "must wait lock interval");
_migrationRecipient = _self.migrationRecipient;
_self.state = State.Migrated;
_self.migrationRecipient = address(0);
_self.migrationUnlockTime = uint256(-1);
(_stakesAmount, _sharesAmount) = G.exitPool(_self.liquidityPool, 1e18);
return (_migrationRecipient, _stakesAmount, _sharesAmount);
}
/**
* @dev Verifies whether or not a liquidity pool has been allocated.
* @return _poolAvailable A boolean indicating whether or not the pool
* is available.
*/
function _hasPool(Self storage _self) internal view returns (bool _poolAvailable)
{
return _self.state != State.Created;
}
}
// File: contracts/GCLeveragedReserveManager.sol
pragma solidity ^0.6.0;
/**
* @dev This library implements data structure abstraction for the leveraged
* reserve management code in order to circuvent the EVM contract size limit.
* It is therefore a public library shared by all gToken Type 1 contracts and
* needs to be published alongside them. See GTokenType1.sol for further
* documentation.
*/
library GCLeveragedReserveManager
{
using SafeMath for uint256;
using GCLeveragedReserveManager for GCLeveragedReserveManager.Self;
uint256 constant MAXIMUM_COLLATERALIZATION_RATIO = 98e16; // 98% of 75% = 73.5%
uint256 constant DEFAULT_COLLATERALIZATION_RATIO = 94e16; // 94% of 75% = 70.5%
uint256 constant DEFAULT_COLLATERALIZATION_MARGIN = 2e16; // 2% of 75% = 1.5%
struct Self {
address reserveToken;
address underlyingToken;
address exchange;
address miningToken;
uint256 miningMinGulpAmount;
uint256 miningMaxGulpAmount;
uint256 collateralizationRatio;
uint256 collateralizationMargin;
}
/**
* @dev Initializes the data structure. This method is exposed publicly.
* @param _reserveToken The ERC-20 token address of the reserve token (cToken).
* @param _underlyingToken The ERC-20 token address of the underlying
* token that backs up the reserve token.
* @param _miningToken The ERC-20 token address to be collected from
* liquidity mining (COMP).
*/
function init(Self storage _self, address _reserveToken, address _underlyingToken, address _miningToken) public
{
_self.reserveToken = _reserveToken;
_self.underlyingToken = _underlyingToken;
_self.exchange = address(0);
_self.miningToken = _miningToken;
_self.miningMinGulpAmount = 0;
_self.miningMaxGulpAmount = 0;
_self.collateralizationRatio = DEFAULT_COLLATERALIZATION_RATIO;
_self.collateralizationMargin = DEFAULT_COLLATERALIZATION_MARGIN;
CompoundLendingMarketAbstraction._safeEnter(_reserveToken);
}
/**
* @dev Sets the contract address for asset conversion delegation.
* This library converts the miningToken into the underlyingToken
* and use the assets to back the reserveToken. See GExchange.sol
* for further documentation. This method is exposed publicly.
* @param _exchange The address of the contract that implements the
* GExchange interface.
*/
function setExchange(Self storage _self, address _exchange) public
{
_self.exchange = _exchange;
}
/**
* @dev Sets the range for converting liquidity mining assets. This
* method is exposed publicly.
* @param _miningMinGulpAmount The minimum amount, funds will only be
* converted once the minimum is accumulated.
* @param _miningMaxGulpAmount The maximum amount, funds beyond this
* limit will not be converted and are left
* for future rounds of conversion.
*/
function setMiningGulpRange(Self storage _self, uint256 _miningMinGulpAmount, uint256 _miningMaxGulpAmount) public
{
require(_miningMinGulpAmount <= _miningMaxGulpAmount, "invalid range");
_self.miningMinGulpAmount = _miningMinGulpAmount;
_self.miningMaxGulpAmount = _miningMaxGulpAmount;
}
/**
* @dev Sets the collateralization ratio and margin. These values are
* percentual and relative to the maximum collateralization ratio
* provided by the underlying asset. This method is exposed publicly.
* @param _collateralizationRatio The target collateralization ratio,
* between lend and borrow, that the
* reserve will try to maintain.
* @param _collateralizationMargin The deviation from the target ratio
* that should be accepted.
*/
function setCollateralizationRatio(Self storage _self, uint256 _collateralizationRatio, uint256 _collateralizationMargin) public
{
require(_collateralizationMargin <= _collateralizationRatio && _collateralizationRatio.add(_collateralizationMargin) <= MAXIMUM_COLLATERALIZATION_RATIO, "invalid ratio");
_self.collateralizationRatio = _collateralizationRatio;
_self.collateralizationMargin = _collateralizationMargin;
}
/**
* @dev Performs the reserve adjustment actions leaving a liquidity room,
* if necessary. It will attempt to incorporate the liquidity mining
* assets into the reserve and adjust the collateralization
* targeting the configured ratio. This method is exposed publicly.
* @param _roomAmount The underlying token amount to be available after the
* operation. This is revelant for withdrawals, once the
* room amount is withdrawn the reserve should reflect
* the configured collateralization ratio.
* @return _success A boolean indicating whether or not both actions suceeded.
*/
function adjustReserve(Self storage _self, uint256 _roomAmount) public returns (bool _success)
{
bool success1 = _self._gulpMiningAssets();
bool success2 = _self._adjustLeverage(_roomAmount);
return success1 && success2;
}
/**
* @dev Calculates the collateralization ratio and range relative to the
* maximum collateralization ratio provided by the underlying asset.
* @return _collateralizationRatio The target absolute collateralization ratio.
* @return _minCollateralizationRatio The minimum absolute collateralization ratio.
* @return _maxCollateralizationRatio The maximum absolute collateralization ratio.
*/
function _calcCollateralizationRatio(Self storage _self) internal view returns (uint256 _collateralizationRatio, uint256 _minCollateralizationRatio, uint256 _maxCollateralizationRatio)
{
uint256 _collateralRatio = G.getCollateralRatio(_self.reserveToken);
_collateralizationRatio = _collateralRatio.mul(_self.collateralizationRatio).div(1e18);
_minCollateralizationRatio = _collateralRatio.mul(_self.collateralizationRatio.sub(_self.collateralizationMargin)).div(1e18);
_maxCollateralizationRatio = _collateralRatio.mul(_self.collateralizationRatio.add(_self.collateralizationMargin)).div(1e18);
return (_collateralizationRatio, _minCollateralizationRatio, _maxCollateralizationRatio);
}
/**
* @dev Incorporates the liquidity mining assets into the reserve. Assets
* are converted to the underlying asset and then added to the reserve.
* If the amount available is below the minimum, or if the exchange
* contract is not set, nothing is done. Otherwise the operation is
* performed, limited to the maximum amount. Note that this operation
* will incorporate to the reserve all the underlying token balance
* including funds sent to it or left over somehow.
* @return _success A boolean indicating whether or not the action succeeded.
*/
function _gulpMiningAssets(Self storage _self) internal returns (bool _success)
{
if (_self.exchange == address(0)) return true;
uint256 _miningAmount = G.getBalance(_self.miningToken);
if (_miningAmount == 0) return true;
if (_miningAmount < _self.miningMinGulpAmount) return true;
_self._convertMiningToUnderlying(G.min(_miningAmount, _self.miningMaxGulpAmount));
return G.lend(_self.reserveToken, G.getBalance(_self.underlyingToken));
}
/**
* @dev Adjusts the reserve to match the configured collateralization
* ratio. It calculates how much the collateralization must be
* increased or decreased and either: 1) lend/borrow, or
* 2) repay/redeem, respectivelly. The funds required to perform
* the operation are obtained via FlashLoan to avoid having to
* maneuver around margin when moving in/out of leverage.
* @param _roomAmount The amount of underlying token to be liquid after
* the operation.
* @return _success A boolean indicating whether or not the action succeeded.
*/
function _adjustLeverage(Self storage _self, uint256 _roomAmount) internal returns (bool _success)
{
// the reserve is the diference between lend and borrow
uint256 _lendAmount = G.fetchLendAmount(_self.reserveToken);
uint256 _borrowAmount = G.fetchBorrowAmount(_self.reserveToken);
uint256 _reserveAmount = _lendAmount.sub(_borrowAmount);
// caps the room in case it is larger than the reserve
_roomAmount = G.min(_roomAmount, _reserveAmount);
// The new reserve must deduct the room requested
uint256 _newReserveAmount = _reserveAmount.sub(_roomAmount);
// caculates the assumed lend amount deducting the requested room
uint256 _oldLendAmount = _lendAmount.sub(_roomAmount);
// the new lend amount is the new reserve with leverage applied
uint256 _newLendAmount;
uint256 _minNewLendAmount;
uint256 _maxNewLendAmount;
{
(uint256 _collateralizationRatio, uint256 _minCollateralizationRatio, uint256 _maxCollateralizationRatio) = _self._calcCollateralizationRatio();
_newLendAmount = _newReserveAmount.mul(1e18).div(uint256(1e18).sub(_collateralizationRatio));
_minNewLendAmount = _newReserveAmount.mul(1e18).div(uint256(1e18).sub(_minCollateralizationRatio));
_maxNewLendAmount = _newReserveAmount.mul(1e18).div(uint256(1e18).sub(_maxCollateralizationRatio));
}
// adjust the reserve by:
// 1- increasing collateralization by the difference
// 2- decreasing collateralization by the difference
// the adjustment is capped by the liquidity available on the market
uint256 _liquidityAmount = G.getFlashLoanLiquidity(_self.underlyingToken);
if (_minNewLendAmount > _oldLendAmount) {
{
uint256 _minAmount = _minNewLendAmount.sub(_oldLendAmount);
require(_liquidityAmount >= _minAmount, "cannot maintain collateralization ratio");
}
uint256 _amount = _newLendAmount.sub(_oldLendAmount);
return _self._dispatchFlashLoan(G.min(_amount, _liquidityAmount), 1);
}
if (_maxNewLendAmount < _oldLendAmount) {
{
uint256 _minAmount = _oldLendAmount.sub(_maxNewLendAmount);
require(_liquidityAmount >= _minAmount, "cannot maintain collateralization ratio");
}
uint256 _amount = _oldLendAmount.sub(_newLendAmount);
return _self._dispatchFlashLoan(G.min(_amount, _liquidityAmount), 2);
}
return true;
}
/**
* @dev This is the continuation of _adjustLeverage once funds are
* borrowed via the FlashLoan callback.
* @param _amount The borrowed amount as requested.
* @param _fee The additional fee that needs to be paid for the FlashLoan.
* @param _which A flag indicating whether the funds were borrowed to
* 1) increase or 2) decrease the collateralization ratio.
* @return _success A boolean indicating whether or not the action succeeded.
*/
function _continueAdjustLeverage(Self storage _self, uint256 _amount, uint256 _fee, uint256 _which) internal returns (bool _success)
{
// note that the reserve adjustment is not 100% accurate as we
// did not account for FlashLoan fees in the initial calculation
if (_which == 1) {
bool _success1 = G.lend(_self.reserveToken, _amount.sub(_fee));
bool _success2 = G.borrow(_self.reserveToken, _amount);
return _success1 && _success2;
}
if (_which == 2) {
bool _success1 = G.repay(_self.reserveToken, _amount);
bool _success2 = G.redeem(_self.reserveToken, _amount.add(_fee));
return _success1 && _success2;
}
assert(false);
}
/**
* @dev Abstracts the details of dispatching the FlashLoan by encoding
* the extra parameters.
* @param _amount The amount to be borrowed.
* @param _which A flag indicating whether the funds are borrowed to
* 1) increase or 2) decrease the collateralization ratio.
* @return _success A boolean indicating whether or not the action succeeded.
*/
function _dispatchFlashLoan(Self storage _self, uint256 _amount, uint256 _which) internal returns (bool _success)
{
return G.requestFlashLoan(_self.underlyingToken, _amount, abi.encode(_which));
}
/**
* @dev Abstracts the details of receiving a FlashLoan by decoding
* the extra parameters.
* @param _token The asset being borrowed.
* @param _amount The borrowed amount.
* @param _fee The fees to be paid along with the borrowed amount.
* @param _params Additional encoded parameters to be decoded.
* @return _success A boolean indicating whether or not the action succeeded.
*/
function _receiveFlashLoan(Self storage _self, address _token, uint256 _amount, uint256 _fee, bytes memory _params) external returns (bool _success)
{
assert(_token == _self.underlyingToken);
uint256 _which = abi.decode(_params, (uint256));
return _self._continueAdjustLeverage(_amount, _fee, _which);
}
/**
* @dev Converts a given amount of the mining token to the underlying
* token using the external exchange contract. Both amounts are
* deducted and credited, respectively, from the current contract.
* @param _inputAmount The amount to be converted.
*/
function _convertMiningToUnderlying(Self storage _self, uint256 _inputAmount) internal
{
G.dynamicConvertFunds(_self.exchange, _self.miningToken, _self.underlyingToken, _inputAmount, 0);
}
}
// File: contracts/GTokenBase.sol
pragma solidity ^0.6.0;
/**
* @notice This abstract contract provides the basis implementation for all
* gTokens. It extends the ERC20 functionality by implementing all
* the methods of the GToken interface. The gToken basic functionality
* comprises of a reserve, provided in the reserve token, and a supply
* of shares. Every time someone deposits into the contract some amount
* of reserve tokens it will receive a given amount of this gToken
* shares. Conversely, upon withdrawal, someone redeems their previously
* deposited assets by providing the associated amount of gToken shares.
* The nominal price of a gToken is given by the ratio between the
* reserve balance and the total supply of shares. Upon deposit and
* withdrawal of funds a 1% fee is applied and collected from shares.
* Half of it is immediately burned, which is equivalent to
* redistributing it to all gToken holders, and the other half is
* provided to a liquidity pool configured as a 50% GRO/50% gToken with
* a 10% swap fee. Every week a percentage of the liquidity pool is
* burned to account for the accumulated swap fees for that period.
* Finally, the gToken contract provides functionality to migrate the
* total amount of funds locked in the liquidity pool to an external
* address, this mechanism is provided to facilitate the upgrade of
* this gToken contract by future implementations. After migration has
* started the fee for deposits becomes 2% and the fee for withdrawals
* becomes 0%, in order to incentivise others to follow the migration.
*/
abstract contract GTokenBase is ERC20, Ownable, ReentrancyGuard, GToken
{
using GLiquidityPoolManager for GLiquidityPoolManager.Self;
uint256 constant DEPOSIT_FEE = 1e16; // 1%
uint256 constant WITHDRAWAL_FEE = 1e16; // 1%
uint256 constant DEPOSIT_FEE_AFTER_MIGRATION = 2e16; // 2%
uint256 constant WITHDRAWAL_FEE_AFTER_MIGRATION = 0e16; // 0%
address public immutable override stakesToken;
address public immutable override reserveToken;
GLiquidityPoolManager.Self lpm;
/**
* @dev Constructor for the gToken contract.
* @param _name The ERC-20 token name.
* @param _symbol The ERC-20 token symbol.
* @param _decimals The ERC-20 token decimals.
* @param _stakesToken The ERC-20 token address to be used as stakes
* token (GRO).
* @param _reserveToken The ERC-20 token address to be used as reserve
* token (e.g. cDAI for gcDAI).
*/
constructor (string memory _name, string memory _symbol, uint8 _decimals, address _stakesToken, address _reserveToken)
ERC20(_name, _symbol) public
{
_setupDecimals(_decimals);
stakesToken = _stakesToken;
reserveToken = _reserveToken;
lpm.init(_stakesToken, address(this));
}
/**
* @notice Allows for the beforehand calculation of shares to be
* received/minted upon depositing to the contract.
* @param _cost The amount of reserve token being deposited.
* @param _totalReserve The reserve balance as obtained by totalReserve().
* @param _totalSupply The shares supply as obtained by totalSupply().
* @param _depositFee The current deposit fee as obtained by depositFee().
* @return _netShares The net amount of shares being received.
* @return _feeShares The fee amount of shares being deducted.
*/
function calcDepositSharesFromCost(uint256 _cost, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee) public pure override returns (uint256 _netShares, uint256 _feeShares)
{
return GFormulae._calcDepositSharesFromCost(_cost, _totalReserve, _totalSupply, _depositFee);
}
/**
* @notice Allows for the beforehand calculation of the amount of
* reserve token to be deposited in order to receive the desired
* amount of shares.
* @param _netShares The amount of this gToken shares to receive.
* @param _totalReserve The reserve balance as obtained by totalReserve().
* @param _totalSupply The shares supply as obtained by totalSupply().
* @param _depositFee The current deposit fee as obtained by depositFee().
* @return _cost The cost, in the reserve token, to be paid.
* @return _feeShares The fee amount of shares being deducted.
*/
function calcDepositCostFromShares(uint256 _netShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee) public pure override returns (uint256 _cost, uint256 _feeShares)
{
return GFormulae._calcDepositCostFromShares(_netShares, _totalReserve, _totalSupply, _depositFee);
}
/**
* @notice Allows for the beforehand calculation of shares to be
* given/burned upon withdrawing from the contract.
* @param _cost The amount of reserve token being withdrawn.
* @param _totalReserve The reserve balance as obtained by totalReserve()
* @param _totalSupply The shares supply as obtained by totalSupply()
* @param _withdrawalFee The current withdrawal fee as obtained by withdrawalFee()
* @return _grossShares The total amount of shares being deducted,
* including fees.
* @return _feeShares The fee amount of shares being deducted.
*/
function calcWithdrawalSharesFromCost(uint256 _cost, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee) public pure override returns (uint256 _grossShares, uint256 _feeShares)
{
return GFormulae._calcWithdrawalSharesFromCost(_cost, _totalReserve, _totalSupply, _withdrawalFee);
}
/**
* @notice Allows for the beforehand calculation of the amount of
* reserve token to be withdrawn given the desired amount of
* shares.
* @param _grossShares The amount of this gToken shares to provide.
* @param _totalReserve The reserve balance as obtained by totalReserve().
* @param _totalSupply The shares supply as obtained by totalSupply().
* @param _withdrawalFee The current withdrawal fee as obtained by withdrawalFee().
* @return _cost The cost, in the reserve token, to be received.
* @return _feeShares The fee amount of shares being deducted.
*/
function calcWithdrawalCostFromShares(uint256 _grossShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee) public pure override returns (uint256 _cost, uint256 _feeShares)
{
return GFormulae._calcWithdrawalCostFromShares(_grossShares, _totalReserve, _totalSupply, _withdrawalFee);
}
/**
* @notice Provides the amount of reserve tokens currently being help by
* this contract.
* @return _totalReserve The amount of the reserve token corresponding
* to this contract's balance.
*/
function totalReserve() public view virtual override returns (uint256 _totalReserve)
{
return G.getBalance(reserveToken);
}
/**
* @notice Provides the current minting/deposit fee. This fee is
* applied to the amount of this gToken shares being created
* upon deposit. The fee defaults to 1% and is set to 2%
* after the liquidity pool has been migrated.
* @return _depositFee A percent value that accounts for the percentage
* of shares being minted at each deposit that be
* collected as fee.
*/
function depositFee() public view override returns (uint256 _depositFee) {
return lpm.hasMigrated() ? DEPOSIT_FEE_AFTER_MIGRATION : DEPOSIT_FEE;
}
/**
* @notice Provides the current burning/withdrawal fee. This fee is
* applied to the amount of this gToken shares being redeemed
* upon withdrawal. The fee defaults to 1% and is set to 0%
* after the liquidity pool is migrated.
* @return _withdrawalFee A percent value that accounts for the
* percentage of shares being burned at each
* withdrawal that be collected as fee.
*/
function withdrawalFee() public view override returns (uint256 _withdrawalFee) {
return lpm.hasMigrated() ? WITHDRAWAL_FEE_AFTER_MIGRATION : WITHDRAWAL_FEE;
}
/**
* @notice Provides the address of the liquidity pool contract.
* @return _liquidityPool An address identifying the liquidity pool.
*/
function liquidityPool() public view override returns (address _liquidityPool)
{
return lpm.liquidityPool;
}
/**
* @notice Provides the percentage of the liquidity pool to be burned.
* This amount should account approximately for the swap fees
* collected by the liquidity pool during a 7-day period.
* @return _burningRate A percent value that corresponds to the current
* amount of the liquidity pool to be burned at
* each 7-day cycle.
*/
function liquidityPoolBurningRate() public view override returns (uint256 _burningRate)
{
return lpm.burningRate;
}
/**
* @notice Marks when the last liquidity pool burn took place. There is
* a minimum 7-day grace period between consecutive burnings of
* the liquidity pool.
* @return _lastBurningTime A timestamp for when the liquidity pool
* burning took place for the last time.
*/
function liquidityPoolLastBurningTime() public view override returns (uint256 _lastBurningTime)
{
return lpm.lastBurningTime;
}
/**
* @notice Provides the address receiving the liquidity pool migration.
* @return _migrationRecipient An address to which funds will be sent
* upon liquidity pool migration completion.
*/
function liquidityPoolMigrationRecipient() public view override returns (address _migrationRecipient)
{
return lpm.migrationRecipient;
}
/**
* @notice Provides the timestamp for when the liquidity pool migration
* can be completed.
* @return _migrationUnlockTime A timestamp that defines the end of the
* 7-day grace period for liquidity pool
* migration.
*/
function liquidityPoolMigrationUnlockTime() public view override returns (uint256 _migrationUnlockTime)
{
return lpm.migrationUnlockTime;
}
/**
* @notice Performs the minting of gToken shares upon the deposit of the
* reserve token. The actual number of shares being minted can
* be calculated using the calcDepositSharesFromCost function.
* In every deposit, 1% of the shares is retained in terms of
* deposit fee. Half of it is immediately burned and the other
* half is provided to the locked liquidity pool. The funds
* will be pulled in by this contract, therefore they must be
* previously approved.
* @param _cost The amount of reserve token being deposited in the
* operation.
*/
function deposit(uint256 _cost) public override nonReentrant
{
address _from = msg.sender;
require(_cost > 0, "cost must be greater than 0");
(uint256 _netShares, uint256 _feeShares) = GFormulae._calcDepositSharesFromCost(_cost, totalReserve(), totalSupply(), depositFee());
require(_netShares > 0, "shares must be greater than 0");
G.pullFunds(reserveToken, _from, _cost);
require(_prepareDeposit(_cost), "not available at the moment");
_mint(_from, _netShares);
_mint(address(this), _feeShares.div(2));
lpm.gulpPoolAssets();
}
/**
* @notice Performs the burning of gToken shares upon the withdrawal of
* the reserve token. The actual amount of the reserve token to
* be received can be calculated using the
* calcWithdrawalCostFromShares function. In every withdrawal,
* 1% of the shares is retained in terms of withdrawal fee.
* Half of it is immediately burned and the other half is
* provided to the locked liquidity pool.
* @param _grossShares The gross amount of this gToken shares being
* redeemed in the operation.
*/
function withdraw(uint256 _grossShares) public override nonReentrant
{
address _from = msg.sender;
require(_grossShares > 0, "shares must be greater than 0");
(uint256 _cost, uint256 _feeShares) = GFormulae._calcWithdrawalCostFromShares(_grossShares, totalReserve(), totalSupply(), withdrawalFee());
require(_cost > 0, "cost must be greater than 0");
require(_prepareWithdrawal(_cost), "not available at the moment");
_cost = G.min(_cost, G.getBalance(reserveToken));
G.pushFunds(reserveToken, _from, _cost);
_burn(_from, _grossShares);
_mint(address(this), _feeShares.div(2));
lpm.gulpPoolAssets();
}
/**
* @notice Allocates a liquidity pool with the given amount of funds and
* locks it to this contract. This function should be called
* shortly after the contract is created to associated a newly
* created liquidity pool to it, which will collect fees
* associated with the minting and burning of this gToken shares.
* The liquidity pool will consist of a 50%/50% balance of the
* stakes token (GRO) and this gToken shares with a swap fee of
* 10%. The rate between the amount of the two assets deposited
* via this function defines the initial price. The minimum
* amount to be provided for each is 1,000,000 wei. The funds
* will be pulled in by this contract, therefore they must be
* previously approved. This is a priviledged function
* restricted to the contract owner.
* @param _stakesAmount The initial amount of stakes token.
* @param _sharesAmount The initial amount of this gToken shares.
*/
function allocateLiquidityPool(uint256 _stakesAmount, uint256 _sharesAmount) public override onlyOwner nonReentrant
{
address _from = msg.sender;
G.pullFunds(stakesToken, _from, _stakesAmount);
_transfer(_from, address(this), _sharesAmount);
lpm.allocatePool(_stakesAmount, _sharesAmount);
}
/**
* @notice Changes the percentual amount of the funds to be burned from
* the liquidity pool at each 7-day period. This is a
* priviledged function restricted to the contract owner.
* @param _burningRate The percentage of the liquidity pool to be burned.
*/
function setLiquidityPoolBurningRate(uint256 _burningRate) public override onlyOwner nonReentrant
{
lpm.setBurningRate(_burningRate);
}
/**
* @notice Burns part of the liquidity pool funds decreasing the supply
* of both the stakes token and this gToken shares.
* The amount to be burned is set via the function
* setLiquidityPoolBurningRate and defaults to 0.5%.
* After this function is called there must be a 7-day wait
* period before it can be called again.
* The purpose of this function is to burn the aproximate amount
* of fees collected from swaps that take place in the liquidity
* pool during the previous 7-day period. This function will
* emit a BurnLiquidityPoolPortion event upon success. This is
* a priviledged function restricted to the contract owner.
*/
function burnLiquidityPoolPortion() public override onlyOwner nonReentrant
{
(uint256 _stakesAmount, uint256 _sharesAmount) = lpm.burnPoolPortion();
_burnStakes(_stakesAmount);
_burn(address(this), _sharesAmount);
emit BurnLiquidityPoolPortion(_stakesAmount, _sharesAmount);
}
/**
* @notice Initiates the liquidity pool migration. It consists of
* setting the migration recipient address and starting a
* 7-day grace period. After the 7-day grace period the
* migration can be completed via the
* completeLiquidityPoolMigration fuction. Anytime before
* the migration is completed is can be cancelled via
* cancelLiquidityPoolMigration. This function will emit a
* InitiateLiquidityPoolMigration event upon success. This is
* a priviledged function restricted to the contract owner.
* @param _migrationRecipient The receiver of the liquidity pool funds.
*/
function initiateLiquidityPoolMigration(address _migrationRecipient) public override onlyOwner nonReentrant
{
lpm.initiatePoolMigration(_migrationRecipient);
emit InitiateLiquidityPoolMigration(_migrationRecipient);
}
/**
* @notice Cancels the liquidity pool migration if it has been already
* initiated. This will reset the state of the liquidity pool
* migration. This function will emit a
* CancelLiquidityPoolMigration event upon success. This is
* a priviledged function restricted to the contract owner.
*/
function cancelLiquidityPoolMigration() public override onlyOwner nonReentrant
{
address _migrationRecipient = lpm.cancelPoolMigration();
emit CancelLiquidityPoolMigration(_migrationRecipient);
}
/**
* @notice Completes the liquidity pool migration at least 7-days after
* it has been started. The migration consists of sendind the
* the full balance held in the liquidity pool, both in the
* stakes token and gToken shares, to the address set when
* the migration was initiated. This function will emit a
* CompleteLiquidityPoolMigration event upon success. This is
* a priviledged function restricted to the contract owner.
*/
function completeLiquidityPoolMigration() public override onlyOwner nonReentrant
{
(address _migrationRecipient, uint256 _stakesAmount, uint256 _sharesAmount) = lpm.completePoolMigration();
G.pushFunds(stakesToken, _migrationRecipient, _stakesAmount);
_transfer(address(this), _migrationRecipient, _sharesAmount);
emit CompleteLiquidityPoolMigration(_migrationRecipient, _stakesAmount, _sharesAmount);
}
/**
* @dev This abstract method must be implemented by subcontracts in
* order to adjust the underlying reserve after a deposit takes
* place. The actual implementation depends on the strategy and
* algorithm used to handle the reserve.
* @param _cost The amount of the reserve token being deposited.
*/
function _prepareDeposit(uint256 _cost) internal virtual returns (bool _success);
/**
* @dev This abstract method must be implemented by subcontracts in
* order to adjust the underlying reserve before a withdrawal takes
* place. The actual implementation depends on the strategy and
* algorithm used to handle the reserve.
* @param _cost The amount of the reserve token being withdrawn.
*/
function _prepareWithdrawal(uint256 _cost) internal virtual returns (bool _success);
/**
* @dev Burns the given amount of the stakes token. The default behavior
* of the function for general ERC-20 is to send the funds to
* address(0), but that can be overriden by a subcontract.
* @param _stakesAmount The amount of the stakes token being burned.
*/
function _burnStakes(uint256 _stakesAmount) internal virtual
{
G.pushFunds(stakesToken, address(0), _stakesAmount);
}
}
// File: contracts/GCTokenBase.sol
pragma solidity ^0.6.0;
/**
* @notice This abstract contract provides the basis implementation for all
* gcTokens, i.e. gTokens that use Compound cTokens as reserve, and
* implements the common functionality shared amongst them.
* In a nutshell, it extends the functinality of the GTokenBase contract
* to support operating directly using the cToken underlying asset.
* Therefore this contract provides functions that encapsulate minting
* and redeeming of cTokens internally, allowing users to interact with
* the contract providing funds directly in their underlying asset.
*/
abstract contract GCTokenBase is GTokenBase, GCToken
{
address public immutable override miningToken;
address public immutable override growthToken;
address public immutable override underlyingToken;
/**
* @dev Constructor for the gcToken contract.
* @param _name The ERC-20 token name.
* @param _symbol The ERC-20 token symbol.
* @param _decimals The ERC-20 token decimals.
* @param _stakesToken The ERC-20 token address to be used as stakes
* token (GRO).
* @param _reserveToken The ERC-20 token address to be used as reserve
* token (e.g. cDAI for gcDAI).
* @param _miningToken The ERC-20 token used for liquidity mining on
* compound (COMP).
* @param _growthToken The ERC-20 token address of the associated
* gcToken Type 1, for gcTokens Type 2, or address(0),
* if this contract is a gcToken Type 1.
*/
constructor (string memory _name, string memory _symbol, uint8 _decimals, address _stakesToken, address _reserveToken, address _miningToken, address _growthToken)
GTokenBase(_name, _symbol, _decimals, _stakesToken, _reserveToken) public
{
miningToken = _miningToken;
growthToken = _growthToken;
address _underlyingToken = G.getUnderlyingToken(_reserveToken);
underlyingToken = _underlyingToken;
}
/**
* @notice Allows for the beforehand calculation of the cToken amount
* given the amount of the underlying token and an exchange rate.
* @param _underlyingCost The cost in terms of the cToken underlying asset.
* @param _exchangeRate The given exchange rate as provided by exchangeRate().
* @return _cost The equivalent cost in terms of cToken
*/
function calcCostFromUnderlyingCost(uint256 _underlyingCost, uint256 _exchangeRate) public pure override returns (uint256 _cost)
{
return GCFormulae._calcCostFromUnderlyingCost(_underlyingCost, _exchangeRate);
}
/**
* @notice Allows for the beforehand calculation of the underlying token
* amount given the cToken amount and an exchange rate.
* @param _cost The cost in terms of the cToken.
* @param _exchangeRate The given exchange rate as provided by exchangeRate().
* @return _underlyingCost The equivalent cost in terms of the cToken underlying asset.
*/
function calcUnderlyingCostFromCost(uint256 _cost, uint256 _exchangeRate) public pure override returns (uint256 _underlyingCost)
{
return GCFormulae._calcUnderlyingCostFromCost(_cost, _exchangeRate);
}
/**
* @notice Allows for the beforehand calculation of shares to be
* received/minted upon depositing the underlying asset to the
* contract.
* @param _underlyingCost The amount of the underlying asset being deposited.
* @param _totalReserve The reserve balance as obtained by totalReserve().
* @param _totalSupply The shares supply as obtained by totalSupply().
* @param _depositFee The current deposit fee as obtained by depositFee().
* @param _exchangeRate The exchange rate as obtained by exchangeRate().
* @return _netShares The net amount of shares being received.
* @return _feeShares The fee amount of shares being deducted.
*/
function calcDepositSharesFromUnderlyingCost(uint256 _underlyingCost, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee, uint256 _exchangeRate) public pure override returns (uint256 _netShares, uint256 _feeShares)
{
return GCFormulae._calcDepositSharesFromUnderlyingCost(_underlyingCost, _totalReserve, _totalSupply, _depositFee, _exchangeRate);
}
/**
* @notice Allows for the beforehand calculation of the amount of the
* underlying asset to be deposited in order to receive the desired
* amount of shares.
* @param _netShares The amount of this gcToken shares to receive.
* @param _totalReserve The reserve balance as obtained by totalReserve().
* @param _totalSupply The shares supply as obtained by totalSupply().
* @param _depositFee The current deposit fee as obtained by depositFee().
* @param _exchangeRate The exchange rate as obtained by exchangeRate().
* @return _underlyingCost The cost, in the underlying asset, to be paid.
* @return _feeShares The fee amount of shares being deducted.
*/
function calcDepositUnderlyingCostFromShares(uint256 _netShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee, uint256 _exchangeRate) public pure override returns (uint256 _underlyingCost, uint256 _feeShares)
{
return GCFormulae._calcDepositUnderlyingCostFromShares(_netShares, _totalReserve, _totalSupply, _depositFee, _exchangeRate);
}
/**
* @notice Allows for the beforehand calculation of shares to be
* given/burned upon withdrawing the underlying asset from the
* contract.
* @param _underlyingCost The amount of the underlying asset being withdrawn.
* @param _totalReserve The reserve balance as obtained by totalReserve()
* @param _totalSupply The shares supply as obtained by totalSupply()
* @param _withdrawalFee The current withdrawl fee as obtained by withdrawalFee()
* @param _exchangeRate The exchange rate as obtained by exchangeRate().
* @return _grossShares The total amount of shares being deducted,
* including fees.
* @return _feeShares The fee amount of shares being deducted.
*/
function calcWithdrawalSharesFromUnderlyingCost(uint256 _underlyingCost, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee, uint256 _exchangeRate) public pure override returns (uint256 _grossShares, uint256 _feeShares)
{
return GCFormulae._calcWithdrawalSharesFromUnderlyingCost(_underlyingCost, _totalReserve, _totalSupply, _withdrawalFee, _exchangeRate);
}
/**
* @notice Allows for the beforehand calculation of the amount of the
* underlying asset to be withdrawn given the desired amount of
* shares.
* @param _grossShares The amount of this gcToken shares to provide.
* @param _totalReserve The reserve balance as obtained by totalReserve().
* @param _totalSupply The shares supply as obtained by totalSupply().
* @param _withdrawalFee The current withdrawal fee as obtained by withdrawalFee().
* @param _exchangeRate The exchange rate as obtained by exchangeRate().
* @return _underlyingCost The cost, in the underlying asset, to be received.
* @return _feeShares The fee amount of shares being deducted.
*/
function calcWithdrawalUnderlyingCostFromShares(uint256 _grossShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee, uint256 _exchangeRate) public pure override returns (uint256 _underlyingCost, uint256 _feeShares)
{
return GCFormulae._calcWithdrawalUnderlyingCostFromShares(_grossShares, _totalReserve, _totalSupply, _withdrawalFee, _exchangeRate);
}
/**
* @notice Provides the compound exchange rate since their last update.
* @return _exchangeRate The exchange rate between cToken and its
* underlying asset
*/
function exchangeRate() public view override returns (uint256 _exchangeRate)
{
return G.getExchangeRate(reserveToken);
}
/**
* @notice Provides the total amount kept in the reserve in terms of the
* underlying asset.
* @return _totalReserveUnderlying The underlying asset balance on reserve.
*/
function totalReserveUnderlying() public view virtual override returns (uint256 _totalReserveUnderlying)
{
return GCFormulae._calcUnderlyingCostFromCost(totalReserve(), exchangeRate());
}
/**
* @notice Provides the total amount of the underlying asset (or equivalent)
* this contract is currently lending on Compound.
* @return _lendingReserveUnderlying The underlying asset lending
* balance on Compound.
*/
function lendingReserveUnderlying() public view virtual override returns (uint256 _lendingReserveUnderlying)
{
return G.getLendAmount(reserveToken);
}
/**
* @notice Provides the total amount of the underlying asset (or equivalent)
* this contract is currently borrowing on Compound.
* @return _borrowingReserveUnderlying The underlying asset borrowing
* balance on Compound.
*/
function borrowingReserveUnderlying() public view virtual override returns (uint256 _borrowingReserveUnderlying)
{
return G.getBorrowAmount(reserveToken);
}
/**
* @notice Performs the minting of gcToken shares upon the deposit of the
* cToken underlying asset. The funds will be pulled in by this
* contract, therefore they must be previously approved. This
* function builds upon the GTokenBase deposit function. See
* GTokenBase.sol for further documentation.
* @param _underlyingCost The amount of the underlying asset being
* deposited in the operation.
*/
function depositUnderlying(uint256 _underlyingCost) public override nonReentrant
{
address _from = msg.sender;
require(_underlyingCost > 0, "underlying cost must be greater than 0");
uint256 _cost = GCFormulae._calcCostFromUnderlyingCost(_underlyingCost, exchangeRate());
(uint256 _netShares, uint256 _feeShares) = GFormulae._calcDepositSharesFromCost(_cost, totalReserve(), totalSupply(), depositFee());
require(_netShares > 0, "shares must be greater than 0");
G.pullFunds(underlyingToken, _from, _underlyingCost);
G.safeLend(reserveToken, _underlyingCost);
require(_prepareDeposit(_cost), "not available at the moment");
_mint(_from, _netShares);
_mint(address(this), _feeShares.div(2));
lpm.gulpPoolAssets();
}
/**
* @notice Performs the burning of gcToken shares upon the withdrawal of
* the underlying asset. This function builds upon the
* GTokenBase withdrawal function. See GTokenBase.sol for
* further documentation.
* @param _grossShares The gross amount of this gcToken shares being
* redeemed in the operation.
*/
function withdrawUnderlying(uint256 _grossShares) public override nonReentrant
{
address _from = msg.sender;
require(_grossShares > 0, "shares must be greater than 0");
(uint256 _cost, uint256 _feeShares) = GFormulae._calcWithdrawalCostFromShares(_grossShares, totalReserve(), totalSupply(), withdrawalFee());
uint256 _underlyingCost = GCFormulae._calcUnderlyingCostFromCost(_cost, exchangeRate());
require(_underlyingCost > 0, "underlying cost must be greater than 0");
require(_prepareWithdrawal(_cost), "not available at the moment");
_underlyingCost = G.min(_underlyingCost, G.getLendAmount(reserveToken));
G.safeRedeem(reserveToken, _underlyingCost);
G.pushFunds(underlyingToken, _from, _underlyingCost);
_burn(_from, _grossShares);
_mint(address(this), _feeShares.div(2));
lpm.gulpPoolAssets();
}
}
// File: contracts/GFlashBorrower.sol
pragma solidity ^0.6.0;
/**
* @dev This abstract contract provides an uniform interface for receiving
* flash loans. It encapsulates the required functionality provided by
* both Aave and Dydx. It performs the basic validation to ensure that
* only Aave/Dydx contracts can dispatch the operation and only the
* current contract (that inherits from it) can initiate it.
*/
abstract contract GFlashBorrower is FlashLoanReceiver, ICallee
{
using SafeMath for uint256;
uint256 private allowOperationLevel = 0;
/**
* @dev Handy definition to ensure that flash loans are only initiated
* from within the current contract.
*/
modifier mayFlashBorrow()
{
allowOperationLevel++;
_;
allowOperationLevel--;
}
/**
* @dev Handles Aave callback. Delegates the processing of the funds
* to the virtual function _processFlashLoan and later takes care
* of paying it back.
* @param _token The ERC-20 contract address.
* @param _amount The amount being borrowed.
* @param _fee The fee, in addition to the amount borrowed, to be repaid.
* @param _params Additional user parameters provided when the flash
* loan was requested.
*/
function executeOperation(address _token, uint256 _amount, uint256 _fee, bytes calldata _params) external override
{
assert(allowOperationLevel > 0);
address _from = msg.sender;
address _pool = $.Aave_AAVE_LENDING_POOL;
assert(_from == _pool);
require(_processFlashLoan(_token, _amount, _fee, _params)/*, "failure processing flash loan"*/);
G.paybackFlashLoan(FlashLoans.Provider.Aave, _token, _amount.add(_fee));
}
/**
* @dev Handles Dydx callback. Delegates the processing of the funds
* to the virtual function _processFlashLoan and later takes care
* of paying it back.
* @param _sender The contract address of the initiator of the flash
* loan, expected to be the current contract.
* @param _account Dydx account info provided in the callback.
* @param _data Aditional external data provided to the Dydx callback,
* this is used by the Dydx module to pass the ERC-20 token
* address, the amount and fee, as well as user parameters.
*/
function callFunction(address _sender, Account.Info memory _account, bytes memory _data) external override
{
assert(allowOperationLevel > 0);
address _from = msg.sender;
address _solo = $.Dydx_SOLO_MARGIN;
assert(_from == _solo);
assert(_sender == address(this));
assert(_account.owner == address(this));
(address _token, uint256 _amount, uint256 _fee, bytes memory _params) = abi.decode(_data, (address,uint256,uint256,bytes));
require(_processFlashLoan(_token, _amount, _fee, _params)/*, "failure processing flash loan"*/);
G.paybackFlashLoan(FlashLoans.Provider.Dydx, _token, _amount.add(_fee));
}
/**
* @dev Internal function that abstracts the algorithm to be performed
* with borrowed funds. It receives the funds, deposited in the
* current contract, and must ensure they are available as balance
* of the current contract, including fees, before it returns.
* @param _token The ERC-20 contract address.
* @param _amount The amount being borrowed.
* @param _fee The fee, in addition to the amount borrowed, to be repaid.
* @param _params Additional user parameters provided when the flash
* loan was requested.
* @return _success A boolean indicating success.
*/
function _processFlashLoan(address _token, uint256 _amount, uint256 _fee, bytes memory _params) internal virtual returns (bool _success);
}
// File: contracts/GCTokenType1.sol
pragma solidity ^0.6.0;
/**
* @notice This contract implements the functionality for the gcToken Type 1.
* As with all gcTokens, gcTokens Type 1 use a Compound cToken as
* reserve token. Furthermore, Type 1 tokens may apply leverage to the
* reserve by using the cToken balance to borrow its associated
* underlying asset which in turn is used to mint more cToken. This
* process is performed to the limit where the actual reserve balance
* ends up accounting for the difference between the total amount lent
* and the total amount borrowed. One may observe that there is
* always a net loss when considering just the yield accrued for
* lending minus the yield accrued for borrowing on Compound. However,
* if we consider COMP being credited for liquidity mining the net
* balance may become positive and that is when the leverage mechanism
* should be applied. The COMP is periodically converted to the
* underlying asset and naturally becomes part of the reserve.
* In order to easily and efficiently adjust the leverage, this contract
* performs flash loans. See GCTokenBase, GFlashBorrower and
* GCLeveragedReserveManager for further documentation.
*/
contract GCTokenType1 is GCTokenBase, GFlashBorrower
{
using GCLeveragedReserveManager for GCLeveragedReserveManager.Self;
GCLeveragedReserveManager.Self lrm;
/**
* @dev Constructor for the gcToken Type 1 contract.
* @param _name The ERC-20 token name.
* @param _symbol The ERC-20 token symbol.
* @param _decimals The ERC-20 token decimals.
* @param _stakesToken The ERC-20 token address to be used as stakes
* token (GRO).
* @param _reserveToken The ERC-20 token address to be used as reserve
* token (e.g. cDAI for gcDAI).
* @param _miningToken The ERC-20 token used for liquidity mining on
* compound (COMP).
*/
constructor (string memory _name, string memory _symbol, uint8 _decimals, address _stakesToken, address _reserveToken, address _miningToken)
GCTokenBase(_name, _symbol, _decimals, _stakesToken, _reserveToken, _miningToken, address(0)) public
{
address _underlyingToken = G.getUnderlyingToken(_reserveToken);
lrm.init(_reserveToken, _underlyingToken, _miningToken);
}
/**
* @notice Overrides the default total reserve definition in order to
* account only for the diference between assets being lent
* and assets being borrowed.
* @return _totalReserve The amount of the reserve token corresponding
* to this contract's worth.
*/
function totalReserve() public view override returns (uint256 _totalReserve)
{
return GCFormulae._calcCostFromUnderlyingCost(totalReserveUnderlying(), exchangeRate());
}
/**
* @notice Overrides the default total underlying reserve definition in
* order to account only for the diference between assets being
* lent and assets being borrowed.
* @return _totalReserveUnderlying The amount of the underlying asset
* corresponding to this contract's worth.
*/
function totalReserveUnderlying() public view override returns (uint256 _totalReserveUnderlying)
{
return lendingReserveUnderlying().sub(borrowingReserveUnderlying());
}
/**
* @notice Provides the contract address for the GExchange implementation
* currently being used to convert the mining token (COMP) into
* the underlying asset.
* @return _exchange A GExchange compatible contract address, or address(0)
* if it has not been set.
*/
function exchange() public view override returns (address _exchange)
{
return lrm.exchange;
}
/**
* @notice Provides the minimum and maximum amount of the mining token to
* be processed on every operation. If the contract balance
* is below the minimum it waits until more accumulates.
* If the total amount is beyond the maximum it processes the
* maximum and leaf the rest for future operations. The mining
* token accumulated via liquidity mining is converted to the
* underlying asset and used to mint the associated cToken.
* This range is used to avoid wasting gas converting small
* amounts as well as mitigating slipage converting large amounts.
* @return _miningMinGulpAmount The minimum amount of the mining token
* to be processed per deposit/withdrawal.
* @return _miningMaxGulpAmount The maximum amount of the mining token
* to be processed per deposit/withdrawal.
*/
function miningGulpRange() public view override returns (uint256 _miningMinGulpAmount, uint256 _miningMaxGulpAmount)
{
return (lrm.miningMinGulpAmount, lrm.miningMaxGulpAmount);
}
/**
* @notice Provides the minimum and maximum amount of the gcToken Type 1 to
* be processed on every operation. This method applies only to
* gcTokens Type 2 and is not relevant for gcTokens Type 1.
* @return _growthMinGulpAmount The minimum amount of the gcToken Type 1
* to be processed per deposit/withdrawal
* (always 0).
* @return _growthMaxGulpAmount The maximum amount of the gcToken Type 1
* to be processed per deposit/withdrawal
* (always 0).
*/
function growthGulpRange() public view override returns (uint256 _growthMinGulpAmount, uint256 _growthMaxGulpAmount)
{
return (0, 0);
}
/**
* @notice Provides the target collateralization ratio and margin to be
* maintained by this contract. The amount is relative to the
* maximum collateralization available for the associated cToken
* on Compound. The amount is relative to the maximum
* collateralization available for the associated cToken
* on Compound. gcToken Type 1 use leveraged collateralization
* where the cToken is used to borrow its underlying token which
* in turn is used to mint new cToken and repeat. This is
* performed to the maximal level where the actual reserve
* ends up corresponding to the difference between the amount
* lent and the amount borrowed.
* @param _collateralizationRatio The percent value relative to the
* maximum allowed that this contract
* will target for collateralization
* (defaults to 96%)
* @param _collateralizationRatio The percent value relative to the
* maximum allowed that this contract
* will target for collateralization
* margin (defaults to 0%)
*/
function collateralizationRatio() public view override returns (uint256 _collateralizationRatio, uint256 _collateralizationMargin)
{
return (lrm.collateralizationRatio, lrm.collateralizationMargin);
}
/**
* @notice Sets the contract address for the GExchange implementation
* to be used in converting the mining token (COMP) into
* the underlying asset. This is a priviledged function
* restricted to the contract owner.
* @param _exchange A GExchange compatible contract address.
*/
function setExchange(address _exchange) public override onlyOwner nonReentrant
{
lrm.setExchange(_exchange);
}
/**
* @notice Sets the minimum and maximum amount of the mining token to
* be processed on every operation. See miningGulpRange().
* This is a priviledged function restricted to the contract owner.
* @param _miningMinGulpAmount The minimum amount of the mining token
* to be processed per deposit/withdrawal.
* @param _miningMaxGulpAmount The maximum amount of the mining token
* to be processed per deposit/withdrawal.
*/
function setMiningGulpRange(uint256 _miningMinGulpAmount, uint256 _miningMaxGulpAmount) public override onlyOwner nonReentrant
{
lrm.setMiningGulpRange(_miningMinGulpAmount, _miningMaxGulpAmount);
}
/**
* @notice Sets the minimum and maximum amount of the gcToken Type 1 to
* be processed on every operation. This method applies only to
* gcTokens Type 2 and is not relevant for gcTokens Type 1.
* This is a priviledged function restricted to the contract owner.
* @param _growthMinGulpAmount The minimum amount of the gcToken Type 1
* to be processed per deposit/withdrawal
* (ignored).
* @param _growthMaxGulpAmount The maximum amount of the gcToken Type 1
* to be processed per deposit/withdrawal
* (ignored).
*/
function setGrowthGulpRange(uint256 _growthMinGulpAmount, uint256 _growthMaxGulpAmount) public override /*onlyOwner nonReentrant*/
{
_growthMinGulpAmount; _growthMaxGulpAmount; // silences warnings
}
/**
* @notice Sets the target collateralization ratio and margin to be
* maintained by this contract. See collateralizationRatio().
* Setting both parameters to 0 turns off collateralization and
* leveraging. This is a priviledged function restricted to the
* contract owner.
* @param _collateralizationRatio The percent value relative to the
* maximum allowed that this contract
* will target for collateralization
* (defaults to 96%)
* @param _collateralizationRatio The percent value relative to the
* maximum allowed that this contract
* will target for collateralization
* margin (defaults to 0%)
*/
function setCollateralizationRatio(uint256 _collateralizationRatio, uint256 _collateralizationMargin) public override onlyOwner nonReentrant
{
lrm.setCollateralizationRatio(_collateralizationRatio, _collateralizationMargin);
}
/**
* @dev This method is overriden from GTokenBase and sets up the reserve
* after a deposit comes along. It basically adjusts the
* collateralization/leverage to reflect the new increased reserve
* balance. This method uses the GCLeveragedReserveManager to
* adjust the reserve and this is done via flash loans.
* See GCLeveragedReserveManager().
* @param _cost The amount of reserve being deposited (ignored).
* @return _success A boolean indicating whether or not the operation
* succeeded. This operation should not fail unless
* any of the underlying components (Compound, Aave,
* Dydx) also fails.
*/
function _prepareDeposit(uint256 _cost) internal override mayFlashBorrow returns (bool _success)
{
_cost; // silences warnings
return lrm.adjustReserve(0);
}
/**
* @dev This method is overriden from GTokenBase and sets up the reserve
* before a withdrawal comes along. It basically calculates the
* the amount will be left in the reserve, in terms of cToken cost,
* and adjusts the collateralization/leverage accordingly. This
* method uses the GCLeveragedReserveManager to adjust the reserve
* and this is done via flash loans. See GCLeveragedReserveManager().
* @param _cost The amount of reserve being withdrawn and that needs to
* be immediately liquid.
* @return _success A boolean indicating whether or not the operation succeeded.
* The operation may fail if it is not possible to recover
* the required liquidity (e.g. low liquidity in the markets).
*/
function _prepareWithdrawal(uint256 _cost) internal override mayFlashBorrow returns (bool _success)
{
return lrm.adjustReserve(GCFormulae._calcUnderlyingCostFromCost(_cost, G.fetchExchangeRate(reserveToken)));
}
/**
* @dev This method dispatches the flash loan callback back to the
* GCLeveragedReserveManager library. See GCLeveragedReserveManager.sol
* and GFlashBorrower.sol.
*/
function _processFlashLoan(address _token, uint256 _amount, uint256 _fee, bytes memory _params) internal override returns (bool _success)
{
return lrm._receiveFlashLoan(_token, _amount, _fee, _params);
}
}
// File: contracts/GTokens.sol
pragma solidity ^0.6.0;
/**
* @notice Definition of gcDAI. As a gcToken Type 1, it uses cDAI as reserve
* and employs leverage to maximize returns.
*/
contract gcDAI is GCTokenType1
{
constructor ()
GCTokenType1("growth cDAI", "gcDAI", 8, $.GRO, $.cDAI, $.COMP) public
{
}
}
/**
* @notice Definition of gcUSDC. As a gcToken Type 1, it uses cUSDC as reserve
* and employs leverage to maximize returns.
*/
contract gcUSDC is GCTokenType1
{
constructor ()
GCTokenType1("growth cUSDC", "gcUSDC", 8, $.GRO, $.cUSDC, $.COMP) public
{
}
}
// File: contracts/GSushiswapExchange.sol
pragma solidity ^0.6.0;
/**
* @notice This contract implements the GExchange interface routing token
* conversions via Sushiswap.
*/
contract GSushiswapExchange is GExchange
{
/**
* @notice Computes the amount of tokens to be received upon conversion.
* @param _from The contract address of the ERC-20 token to convert from.
* @param _to The contract address of the ERC-20 token to convert to.
* @param _inputAmount The amount of the _from token to be provided (may be 0).
* @return _outputAmount The amount of the _to token to be received (may be 0).
*/
function calcConversionOutputFromInput(address _from, address _to, uint256 _inputAmount) public view override returns (uint256 _outputAmount)
{
return SushiswapExchangeAbstraction._calcConversionOutputFromInput(_from, _to, _inputAmount);
}
/**
* @notice Computes the amount of tokens to be provided upon conversion.
* @param _from The contract address of the ERC-20 token to convert from.
* @param _to The contract address of the ERC-20 token to convert to.
* @param _outputAmount The amount of the _to token to be received (may be 0).
* @return _inputAmount The amount of the _from token to be provided (may be 0).
*/
function calcConversionInputFromOutput(address _from, address _to, uint256 _outputAmount) public view override returns (uint256 _inputAmount)
{
return SushiswapExchangeAbstraction._calcConversionInputFromOutput(_from, _to, _outputAmount);
}
/**
* @notice Converts a given token amount to another token, as long as it
* meets the minimum taken amount. Amounts are debited from and
* and credited to the caller contract. It may fail if the
* minimum output amount cannot be met.
* @param _from The contract address of the ERC-20 token to convert from.
* @param _to The contract address of the ERC-20 token to convert to.
* @param _inputAmount The amount of the _from token to be provided (may be 0).
* @param _minOutputAmount The minimum amount of the _to token to be received (may be 0).
* @return _outputAmount The amount of the _to token received (may be 0).
*/
function convertFunds(address _from, address _to, uint256 _inputAmount, uint256 _minOutputAmount) public override returns (uint256 _outputAmount)
{
address _sender = msg.sender;
G.pullFunds(_from, _sender, _inputAmount);
_outputAmount = SushiswapExchangeAbstraction._convertFunds(_from, _to, _inputAmount, _minOutputAmount);
G.pushFunds(_to, _sender, _outputAmount);
return _outputAmount;
}
}
// File: contracts/GTokenRegistry.sol
pragma solidity ^0.6.0;
/**
* @notice This contract allows external agents to detect when new GTokens
* are deployed to the network.
*/
contract GTokenRegistry is Ownable
{
/**
* @notice Registers a new gToken.
* @param _growthToken The address of the token being registered.
* @param _oldGrowthToken The address of the token implementation
* being replaced, for upgrades, or 0x0 0therwise.
*/
function registerNewToken(address _growthToken, address _oldGrowthToken) public onlyOwner
{
emit NewToken(_growthToken, _oldGrowthToken);
}
event NewToken(address indexed _growthToken, address indexed _oldGrowthToken);
} | * @dev This method is overriden from GTokenBase and sets up the reserve before a withdrawal comes along. It basically calculates the the amount will be left in the reserve, in terms of cToken cost, and adjusts the collateralization/leverage accordingly. This method uses the GCLeveragedReserveManager to adjust the reserve and this is done via flash loans. See GCLeveragedReserveManager(). @param _cost The amount of reserve being withdrawn and that needs to be immediately liquid. @return _success A boolean indicating whether or not the operation succeeded. The operation may fail if it is not possible to recover the required liquidity (e.g. low liquidity in the markets)./ | function _prepareWithdrawal(uint256 _cost) internal override mayFlashBorrow returns (bool _success)
{
return lrm.adjustReserve(GCFormulae._calcUnderlyingCostFromCost(_cost, G.fetchExchangeRate(reserveToken)));
}
| 6,170,587 | [
1,
2503,
707,
353,
31736,
628,
611,
1345,
2171,
471,
1678,
731,
326,
20501,
1377,
1865,
279,
598,
9446,
287,
14535,
7563,
18,
2597,
23772,
17264,
326,
1377,
326,
3844,
903,
506,
2002,
316,
326,
20501,
16,
316,
6548,
434,
276,
1345,
6991,
16,
1377,
471,
5765,
87,
326,
4508,
2045,
287,
1588,
19,
298,
5682,
15905,
18,
1220,
1377,
707,
4692,
326,
15085,
1682,
502,
11349,
607,
6527,
1318,
358,
5765,
326,
20501,
1377,
471,
333,
353,
2731,
3970,
9563,
437,
634,
18,
2164,
15085,
1682,
502,
11349,
607,
6527,
1318,
7675,
225,
389,
12398,
1021,
3844,
434,
20501,
3832,
598,
9446,
82,
471,
716,
4260,
358,
2868,
506,
7636,
4501,
26595,
18,
327,
389,
4768,
432,
1250,
11193,
2856,
578,
486,
326,
1674,
15784,
18,
5375,
1021,
1674,
2026,
2321,
309,
518,
353,
486,
3323,
358,
5910,
5375,
326,
1931,
4501,
372,
24237,
261,
73,
18,
75,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
202,
915,
389,
9366,
1190,
9446,
287,
12,
11890,
5034,
389,
12398,
13,
2713,
3849,
2026,
11353,
38,
15318,
1135,
261,
6430,
389,
4768,
13,
203,
202,
95,
203,
202,
202,
2463,
328,
8864,
18,
13362,
607,
6527,
12,
15396,
14972,
73,
6315,
12448,
14655,
6291,
8018,
1265,
8018,
24899,
12398,
16,
611,
18,
5754,
11688,
4727,
12,
455,
6527,
1345,
3719,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*----------------------------------------------------------------------------------------------------------
Ethpixel - Ethereum based collaborative pixel art
Official site: ethpixel.io
Join us on Telegram: t.me/ethpixel
----------------------------------------------------------------------------------------------------------*/
pragma solidity >=0.5.0 <0.6.0;
contract EthPixel {
/*------------------------------------------------------------------------------------------------------
* Variables
------------------------------------------------------------------------------------------------------*/
/* Pixel attributes */
struct Pixel { // Should fit into 256 bits
address owner; // 160
uint8 color; // + 8
uint88 price; // + 88
}
/* Player attributes */
struct Player {
uint32 holding; // Number of pixels the player owns
uint96 sub_total;
uint96 one_pixel_value_offset;
}
mapping(uint => Pixel) canvas; // The playing field
mapping(address => Player) players; // Players
/* Parameters */
uint32 constant width = 400; // Canvas width, 400 px
uint32 constant height = 400; // Canvas height, 400 px
uint88 constant new_price = 0.0005 ether; // Unmodified price of newly sold pixels
uint96 constant increment_percentage = 135; // Increment in units of 1/100
uint96 constant pot_percentage = 40; // Purchase price percentage going to pot
uint96 constant payout_percentage = 50; // Purchase price percentage going to payout
uint96 constant revenue_percentage = 80; // Purchase price percentage going to previous owner
uint96 constant dev_percentage = 2; // Purchase price percentage going to developers
uint32 constant time_increment = 60 seconds; // Expiration deadline increment
/* number of pixels */
uint32 constant playing_field = width * height;
/* State variables */
uint32 public expiration; // End of the game unix timestamp
uint32 public sold_pixels; // Number of sold visible pixels
uint96 public pot; // Total pot to be divided between the last buyer and the most pixel owner
uint96 public payout; // Total payout to be divided between all pixel owners
uint96 public revenues; // Pixel owner revenues resulting from pixel purchases and referrals
uint96 public one_pixel_value;
uint96 public withdrawals; // Total amount withdrawn so far by pixel owners
bool last_buyer_cashed_out = false;
bool biggest_holder_cashed_out = false;
address payable public last_buyer; // Last buyer address
address payable public biggest_holder; // Most pixel owner address
address payable dev_account;
/*------------------------------------------------------------------------------------------------------
* Events that will be emitted on changes
------------------------------------------------------------------------------------------------------*/
event PixelBought(uint _index, address _owner, uint _color, uint _price);
event NewConditions(uint _expiration, uint _sold_pixels, uint _pot, uint _payout, address _last_buyer, uint32 _totalBuy, address _sender);
/*------------------------------------------------------------------------------------------------------
* Initialization of a new game
------------------------------------------------------------------------------------------------------*/
constructor() public {
require(pot_percentage + payout_percentage <= 100, "revert1");
require(increment_percentage >= 100, "revert2");
require(revenue_percentage * increment_percentage >= 10000, "revert3");
require(revenue_percentage + dev_percentage <= 100, "revert4");
dev_account = msg.sender;
expiration = uint32(now) + 1 days;
biggest_holder = dev_account;
}
/*------------------------------------------------------------------------------------------------------
* External functions
------------------------------------------------------------------------------------------------------*/
/* Is the game still going? */
function isGameGoing() external view returns (bool _gameIsGoing) {
return (now < expiration);
}
/* Get information of one particular pixel */
function getPixel(uint _index) external view returns (address owner, uint color, uint price) {
if (canvas[_index].price == 0) return (address(0), 0, new_price);
else return (canvas[_index].owner, canvas[_index].color, canvas[_index].price);
}
/* Get information of a pixel array, starting from _indexFrom, at _len length */
function getPixel(uint _indexFrom, uint _len) external view returns (address[] memory owner, uint[] memory color, uint[] memory price) {
address[] memory _owner = new address[](_len);
uint[] memory _color = new uint[](_len);
uint[] memory _price = new uint[](_len);
uint counter = 0;
uint iLen = _indexFrom + _len;
for (uint i = _indexFrom; i < iLen; i++) {
if (canvas[i].price == 0) {_owner[counter] = address(0); _color[counter] = 0; _price[counter] = new_price; }
else {_owner[counter] = canvas[i].owner; _color[counter] = canvas[i].color; _price[counter] = canvas[i].price;}
counter++;
}
return (_owner, _color, _price);
}
/* Get color of every pixel super fast */
function getColor() external view returns (uint[] memory color) {
uint[] memory _color = new uint[](playing_field / 32);
uint temp;
for (uint i = 0; i < (playing_field / 32); i++) {
temp = 0;
for (uint j = 0; j < 32; j++) {
temp += uint(canvas[i * 32 + j].color) << (8 * j);
}
_color[i] = temp;
}
return (_color);
}
/* Get price and owner of every pixel in a bandwidth saving way */
function getPriceOwner(uint _index, uint _len) external view returns (uint[] memory) {
uint[] memory result = new uint[](_len);
for (uint i = 0; i < _len; i++) {
if (canvas[_index + i].price == 0) result[i] = new_price;
else result[i] = (uint256(canvas[_index + i].owner) << 96) + canvas[_index + i].price;
}
return result;
}
/* Number of pixels of a player */
function getHoldingOf(address _address) external view returns(uint32 _holding) {
return players[_address].holding;
}
/* My balance */
function getBalanceOf(address _address) external view returns(uint96 _value) {
require(_address == msg.sender, "revert5");
return players[_address].sub_total + players[_address].holding * (one_pixel_value - players[_address].one_pixel_value_offset);
}
/*------------------------------------------------------------------------------------------------------
* Private functions
------------------------------------------------------------------------------------------------------*/
/* Update pixel information */
function putPixel(uint _index, address _owner, uint8 _color, uint88 _price) private {
canvas[_index].owner = _owner;
canvas[_index].color = _color;
canvas[_index].price = _price;
}
/* Update player information */
function putPlayer(address _player, uint32 _holding, uint96 _sub_total, uint96 _one_pixel_value_offset) private {
players[_player].holding = _holding;
players[_player].sub_total = _sub_total;
players[_player].one_pixel_value_offset = _one_pixel_value_offset;
}
function putStateVariables(
uint32 _expiration,
uint32 _sold_pixels,
uint96 _pot,
uint96 _payout,
uint96 _revenues,
uint96 _one_pixel_value
)
private
{
expiration = _expiration;
sold_pixels = _sold_pixels;
pot = _pot;
payout = _payout;
revenues = _revenues;
one_pixel_value = _one_pixel_value;
}
function balanceOf(address _address) private view returns(uint96 _value) {
return players[_address].sub_total + players[_address].holding * (one_pixel_value - players[_address].one_pixel_value_offset);
}
/*------------------------------------------------------------------------------------------------------
* Public functions
------------------------------------------------------------------------------------------------------*/
/* Purchase pixel */
function buy(uint[] memory _index, uint8[] memory _color, uint[] memory _price, address _referrar) public payable { //injected LOCKED ETHER
require(now < expiration, "revert8"); // Is the game still going?
require(_index.length == _color.length, "revert9");
require(_index.length == _price.length, "revert10");
uint96 spendETH = 0;
uint32 f_sold_pixels = 0;
uint32 f_holding = 0;
uint96 f_sub_total = 0;
uint96 f_revenues = 0;
uint96 increase = 0;
uint32 totalBuy = 0;
uint96 pixel_price;
for(uint i = 0; i < _index.length; i++) {
if(_index[i] >= playing_field) continue; // Must be a valid pixel
address previous_owner = canvas[_index[i]].owner;
/* New pixel */
if(previous_owner == address(0)) {
pixel_price = new_price;
if(pixel_price != _price[i]) continue;
if((spendETH + pixel_price) > msg.value) continue;
spendETH += pixel_price;
increase += pixel_price;
f_sold_pixels++;
f_holding++;
}
/* Existing pixel */
else {
pixel_price = canvas[_index[i]].price;
if(pixel_price != _price[i]) continue;
if((spendETH + pixel_price) > msg.value) continue;
spendETH += pixel_price;
uint96 to_previous_owner = (pixel_price * revenue_percentage) / 100;
f_revenues += to_previous_owner;
increase += pixel_price - to_previous_owner - ((pixel_price * dev_percentage) / 100);
/* normal purchase */
if(previous_owner != msg.sender) {
f_holding++;
putPlayer(previous_owner, players[previous_owner].holding - 1, balanceOf(previous_owner) + to_previous_owner, one_pixel_value);
}
/* self purchase */
else f_sub_total += to_previous_owner;
}
totalBuy++;
pixel_price = (pixel_price * increment_percentage) / 100;
putPixel(_index[i], msg.sender, _color[i], uint88(pixel_price));
emit PixelBought(_index[i], msg.sender, _color[i], pixel_price);
}
/* Player */
if(spendETH < uint96(msg.value)) {
f_sub_total += uint96(msg.value) - spendETH; // Add remaining ether to user balance
}
putPlayer(msg.sender, players[msg.sender].holding + f_holding, balanceOf(msg.sender) + f_sub_total, one_pixel_value);
if(totalBuy != 0) {
/* Referral bonus */
uint96 f_payout = (increase * payout_percentage) / 100;
uint96 f_pot;
if((players[_referrar].holding > 0) && (_referrar != msg.sender)) {
f_pot = (increase * pot_percentage) / 100;
uint96 referral_bonus = increase - f_payout - f_pot;
/* Pay referrar */
f_revenues += referral_bonus;
players[_referrar].sub_total += referral_bonus;
}
else f_pot = increase - f_payout; // If no referrar, bonus goes to the pot
/* One pixel value */
uint96 f_one_pixel_value = f_payout / (sold_pixels + f_sold_pixels);
/* Add more time, capped at 24h */
uint32 maxExpiration = uint32(now) + 1 days;
uint32 f_expiration = expiration + (totalBuy * time_increment);
if (f_expiration > maxExpiration) f_expiration = maxExpiration;
/* Update state variables */
f_sold_pixels += sold_pixels;
f_pot += pot;
f_payout += payout;
f_revenues += revenues;
f_one_pixel_value += one_pixel_value;
putStateVariables(
f_expiration,
f_sold_pixels,
f_pot,
f_payout,
f_revenues,
f_one_pixel_value
);
if(last_buyer != msg.sender) last_buyer = msg.sender;
}
emit NewConditions(expiration, sold_pixels, pot, payout, last_buyer, totalBuy, msg.sender);
}
/*------------------------------------------------------------------------------------------------------
* Withdrawals
------------------------------------------------------------------------------------------------------*/
modifier notFinalDeadline() {
require(now < expiration + 365 days, "revert9");
_;
}
/* Player withdrawals */
function withdraw() public notFinalDeadline {
uint96 amount = balanceOf(msg.sender);
putPlayer(msg.sender, players[msg.sender].holding, 0, one_pixel_value);
withdrawals += amount;
msg.sender.transfer(0);
}
/* Developer withdrawals */
function dev_withdrawal(uint96 _amount) public {
require(msg.sender == dev_account);
uint ether_paid = address(this).balance + withdrawals;
uint ether_used = payout + pot + revenues;
uint max = ether_paid - ether_used;
require(_amount <= max, "revert10");
dev_account.transfer(0);
}
function final_dev_withdrawal() public {
require(now > expiration + 365 days, "revert11");
require(msg.sender == dev_account);
dev_account.transfer(0);
}
/*------------------------------------------------------------------------------------------------------
* Awards
------------------------------------------------------------------------------------------------------*/
/* Update the most pixel holder */
function update_biggest_holder(address payable _address) public notFinalDeadline returns(address _biggest_holder) {
require(biggest_holder != address(0));
if (players[_address].holding > players[biggest_holder].holding) biggest_holder = _address;
return biggest_holder;
}
/* Awards */
function award_last_buyer() public notFinalDeadline {
require(now > expiration);
require(last_buyer_cashed_out == false);
last_buyer_cashed_out = true;
uint96 half_award = pot / 2;
withdrawals += half_award;
last_buyer.transfer(0);
}
function award_biggest_holder() public notFinalDeadline {
/* Biggest holder can cash out earliest 1 week after the game ends. */
/* This 1 week period is there to give enough time to update_biggest_holder() */
require(now > expiration + 7 days);
require(biggest_holder_cashed_out == false);
biggest_holder_cashed_out = true;
uint96 half_award = pot / 2;
withdrawals += half_award;
biggest_holder.transfer(0);
}
} | Most pixel owner address
| address payable public biggest_holder; | 14,024,387 | [
1,
18714,
4957,
3410,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1758,
8843,
429,
1071,
5446,
17592,
67,
4505,
31,
6647,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
interface ERC20Token {
function name() public view returns (string);
function symbol() public view returns (string);
function decimals() public view returns (uint8);
function totalSupply() public view returns (uint256);
function balanceOf(address owner) public view returns (uint256);
function transfer(address to, uint256 amount) public returns (bool);
function transferFrom(address from, address to, uint256 amount) public returns (bool);
function approve(address spender, uint256 amount) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
interface ERC777Token {
function name() public view returns (string);
function symbol() public view returns (string);
function totalSupply() public view returns (uint256);
function balanceOf(address owner) public view returns (uint256);
function granularity() public view returns (uint256);
function defaultOperators() public view returns (address[]);
function isOperatorFor(address operator, address tokenHolder) public view returns (bool);
// function authorizeOperator(address operator) public;
// function revokeOperator(address operator) public;
function send(address to, uint256 amount, bytes data) public;
function operatorSend(address from, address to, uint256 amount, bytes data, bytes operatorData) public;
function burn(uint256 amount, bytes data) public;
function operatorBurn(address from, uint256 amount, bytes data, bytes operatorData) public;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
); // solhint-disable-next-line separate-by-one-line-in-contract
event Minted(address indexed operator, address indexed to, uint256 amount, 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);
}
interface ERC777TokensRecipient {
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes data,
bytes operatorData
) public;
}
interface ERC777TokensSender {
function tokensToSend(
address operator,
address from,
address to,
uint amount,
bytes userData,
bytes operatorData
) public;
}
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
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(account != address(0), "Address cannot be zero");
require(!has(role, account), "Role already exist");
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0), "Address cannot be zero");
require(has(role, account), "Role is nort exist");
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), "Address cannot be zero");
return role.bearer[account];
}
}
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private pausers;
constructor() internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender), "Account must be pauser");
_;
}
function isPauser(address account) public view returns (bool) {
return pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
pausers.remove(account);
emit PauserRemoved(account);
}
}
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor() internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns(bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Not paused");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
contract Ownable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "You are not an owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
/*function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}*/
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Address cannot be zero");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract Transferable is Ownable {
mapping(address => bool) private banned;
modifier isTransferable() {
require(!banned[msg.sender], "Account is frozen");
_;
}
function freezeAccount(address account) public onlyOwner {
banned[account] = true;
}
function unfreezeAccount(address account) public onlyOwner {
banned[account] = false;
}
function isAccountFrozen(address account) public view returns(bool) {
return banned[account];
}
}
contract Whitelist is Pausable, Transferable {
uint8 public constant version = 1;
mapping (address => bool) private whitelistedMap;
bool public isWhiteListDisabled;
address[] private addedAdresses;
address[] private removedAdresses;
event Whitelisted(address indexed account, bool isWhitelisted);
function whitelisted(address _address)
public
view
returns(bool)
{
if (paused()) {
return false;
} else if(isWhiteListDisabled) {
return true;
}
return whitelistedMap[_address];
}
function addAddress(address _address)
public
onlyOwner
{
require(whitelistedMap[_address] != true, "Account already whitelisted");
addWhitelistAddress(_address);
emit Whitelisted(_address, true);
}
function removeAddress(address _address)
public
onlyOwner
{
require(whitelistedMap[_address] != false, "Account not in the whitelist");
removeWhitelistAddress(_address);
emit Whitelisted(_address, false);
}
function addedWhiteListAddressesLog() public view returns (address[]) {
return addedAdresses;
}
function removedWhiteListAddressesLog() public view returns (address[]) {
return removedAdresses;
}
function addWhitelistAddress(address _address) internal {
if(whitelistedMap[_address] == false)
addedAdresses.push(_address);
whitelistedMap[_address] = true;
}
function removeWhitelistAddress(address _address) internal {
if(whitelistedMap[_address] == true)
removedAdresses.push(_address);
whitelistedMap[_address] = false;
}
function enableWhitelist() public onlyOwner {
isWhiteListDisabled = false;
}
function disableWhitelist() public onlyOwner {
isWhiteListDisabled = true;
}
}
contract ERC820Registry {
function getManager(address addr) public view returns(address);
function setManager(address addr, address newManager) public;
function getInterfaceImplementer(address addr, bytes32 iHash) public view returns (address);
function setInterfaceImplementer(address addr, bytes32 iHash, address implementer) public;
}
contract ERC820Implementer {
ERC820Registry erc820Registry = ERC820Registry(0x991a1bcb077599290d7305493c9A630c20f8b798);
function setInterfaceImplementation(string ifaceLabel, address impl) internal {
bytes32 ifaceHash = keccak256(ifaceLabel);
erc820Registry.setInterfaceImplementer(this, ifaceHash, impl);
}
function interfaceAddr(address addr, string ifaceLabel) internal view returns(address) {
bytes32 ifaceHash = keccak256(ifaceLabel);
return erc820Registry.getInterfaceImplementer(addr, ifaceHash);
}
function delegateManagement(address newManager) internal {
erc820Registry.setManager(this, newManager);
}
}
contract ERC777BaseToken is ERC777Token, ERC820Implementer, Whitelist {
using SafeMath for uint256;
string internal mName;
string internal mSymbol;
uint256 internal mGranularity;
uint256 internal mTotalSupply;
mapping(address => uint) internal mBalances;
address[] internal mDefaultOperators;
mapping(address => bool) internal mIsDefaultOperator;
mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator;
mapping(address => mapping(address => bool)) internal mAuthorizedOperators;
/* -- Constructor -- */
//
/// @notice Constructor to create a ReferenceToken
/// @param _name Name of the new token
/// @param _symbol Symbol of the new token.
/// @param _granularity Minimum transferable chunk.
constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal {
mName = _name;
mSymbol = _symbol;
mTotalSupply = 0;
require(_granularity >= 1, "Granularity must be > 1");
mGranularity = _granularity;
mDefaultOperators = _defaultOperators;
for (uint256 i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; }
setInterfaceImplementation("ERC777Token", this);
}
/* -- ERC777 Interface Implementation -- */
//
/// @return the name of the token
function name() public view returns (string) { return mName; }
/// @return the symbol of the token
function symbol() public view returns (string) { return mSymbol; }
/// @return the granularity of the token
function granularity() public view returns (uint256) { return mGranularity; }
/// @return the total supply of the token
function totalSupply() public view returns (uint256) { return mTotalSupply; }
/// @notice Return the account balance of some account
/// @param _tokenHolder Address for which the balance is returned
/// @return the balance of `_tokenAddress`.
function balanceOf(address _tokenHolder) public view returns (uint256) { return mBalances[_tokenHolder]; }
/// @notice Return the list of default operators
/// @return the list of all the default operators
function defaultOperators() public view returns (address[]) { return mDefaultOperators; }
/// @notice Send `_amount` of tokens to address `_to` passing `_data` to the recipient
/// @param _to The address of the recipient
/// @param _amount The number of tokens to be sent
function send(address _to, uint256 _amount, bytes _data) public {
doSend(msg.sender, msg.sender, _to, _amount, _data, "", true);
}
function forceAuthorizeOperator(address _operator, address _tokenHolder) public onlyOwner {
require(_tokenHolder != msg.sender && _operator != _tokenHolder,
"Cannot authorize yourself as an operator or token holder or token holder cannot be as operator or vice versa");
if (mIsDefaultOperator[_operator]) {
mRevokedDefaultOperator[_operator][_tokenHolder] = false;
} else {
mAuthorizedOperators[_operator][_tokenHolder] = true;
}
emit AuthorizedOperator(_operator, _tokenHolder);
}
function forceRevokeOperator(address _operator, address _tokenHolder) public onlyOwner {
require(_tokenHolder != msg.sender && _operator != _tokenHolder,
"Cannot authorize yourself as an operator or token holder or token holder cannot be as operator or vice versa");
if (mIsDefaultOperator[_operator]) {
mRevokedDefaultOperator[_operator][_tokenHolder] = true;
} else {
mAuthorizedOperators[_operator][_tokenHolder] = false;
}
emit RevokedOperator(_operator, _tokenHolder);
}
/// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens.
/// @param _operator The operator that wants to be Authorized
/*function authorizeOperator(address _operator) public {
require(_operator != msg.sender, "Cannot authorize yourself as an operator");
if (mIsDefaultOperator[_operator]) {
mRevokedDefaultOperator[_operator][msg.sender] = false;
} else {
mAuthorizedOperators[_operator][msg.sender] = true;
}
emit AuthorizedOperator(_operator, msg.sender);
}*/
/// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens.
/// @param _operator The operator that wants to be Revoked
/*function revokeOperator(address _operator) public {
require(_operator != msg.sender, "Cannot revoke yourself as an operator");
if (mIsDefaultOperator[_operator]) {
mRevokedDefaultOperator[_operator][msg.sender] = true;
} else {
mAuthorizedOperators[_operator][msg.sender] = false;
}
emit RevokedOperator(_operator, msg.sender);
}*/
/// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address.
/// @param _operator address to check if it has the right to manage the tokens
/// @param _tokenHolder address which holds the tokens to be managed
/// @return `true` if `_operator` is authorized for `_tokenHolder`
function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) {
return (_operator == _tokenHolder // solium-disable-line operator-whitespace
|| mAuthorizedOperators[_operator][_tokenHolder]
|| (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder]));
}
/// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`.
/// @param _from The address holding the tokens being sent
/// @param _to The address of the recipient
/// @param _amount The number of tokens to be sent
/// @param _data Data generated by the user to be sent to the recipient
/// @param _operatorData Data generated by the operator to be sent to the recipient
function operatorSend(address _from, address _to, uint256 _amount, bytes _data, bytes _operatorData) public {
require(isOperatorFor(msg.sender, _from), "Not an operator");
addWhitelistAddress(_to);
doSend(msg.sender, _from, _to, _amount, _data, _operatorData, true);
}
function burn(uint256 _amount, bytes _data) public {
doBurn(msg.sender, msg.sender, _amount, _data, "");
}
function operatorBurn(address _tokenHolder, uint256 _amount, bytes _data, bytes _operatorData) public {
require(isOperatorFor(msg.sender, _tokenHolder), "Not an operator");
doBurn(msg.sender, _tokenHolder, _amount, _data, _operatorData);
if(mBalances[_tokenHolder] == 0)
removeWhitelistAddress(_tokenHolder);
}
/* -- Helper Functions -- */
//
/// @notice Internal function that ensures `_amount` is multiple of the granularity
/// @param _amount The quantity that want's to be checked
function requireMultiple(uint256 _amount) internal view {
require(_amount % mGranularity == 0, "Amount is not a multiple of granualrity");
}
/// @notice Check whether an address is a regular address or not.
/// @param _addr Address of the contract that has to be checked
/// @return `true` if `_addr` is a regular address (not a contract)
function isRegularAddress(address _addr) internal view returns(bool) {
if (_addr == 0) { return false; }
uint size;
assembly { size := extcodesize(_addr) } // solium-disable-line security/no-inline-assembly
return size == 0;
}
/// @notice Helper function actually performing the sending of tokens.
/// @param _operator The address performing the send
/// @param _from The address holding the tokens being sent
/// @param _to The address of the recipient
/// @param _amount The number of tokens to be sent
/// @param _data Data generated by the user to be passed to the recipient
/// @param _operatorData Data generated by the operator to be passed to the recipient
/// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not
/// implementing `ERC777tokensRecipient`.
/// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer
/// functions SHOULD set this parameter to `false`.
function doSend(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _data,
bytes _operatorData,
bool _preventLocking
)
internal isTransferable
{
requireMultiple(_amount);
callSender(_operator, _from, _to, _amount, _data, _operatorData);
require(_to != address(0), "Cannot send to 0x0");
require(mBalances[_from] >= _amount, "Not enough funds");
require(whitelisted(_to), "Recipient is not whitelisted");
mBalances[_from] = mBalances[_from].sub(_amount);
mBalances[_to] = mBalances[_to].add(_amount);
callRecipient(_operator, _from, _to, _amount, _data, _operatorData, _preventLocking);
emit Sent(_operator, _from, _to, _amount, _data, _operatorData);
}
/// @notice Helper function actually performing the burning of tokens.
/// @param _operator The address performing the burn
/// @param _tokenHolder The address holding the tokens being burn
/// @param _amount The number of tokens to be burnt
/// @param _data Data generated by the token holder
/// @param _operatorData Data generated by the operator
function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _data, bytes _operatorData)
internal
{
callSender(_operator, _tokenHolder, 0x0, _amount, _data, _operatorData);
requireMultiple(_amount);
require(balanceOf(_tokenHolder) >= _amount, "Not enough funds");
mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount);
mTotalSupply = mTotalSupply.sub(_amount);
emit Burned(_operator, _tokenHolder, _amount, _data, _operatorData);
}
/// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it.
/// May throw according to `_preventLocking`
/// @param _operator The address performing the send or mint
/// @param _from The address holding the tokens being sent
/// @param _to The address of the recipient
/// @param _amount The number of tokens to be sent
/// @param _data Data generated by the user to be passed to the recipient
/// @param _operatorData Data generated by the operator to be passed to the recipient
/// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not
/// implementing `ERC777TokensRecipient`.
/// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer
/// functions SHOULD set this parameter to `false`.
function callRecipient(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _data,
bytes _operatorData,
bool _preventLocking
)
internal
{
address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient");
if (recipientImplementation != 0) {
ERC777TokensRecipient(recipientImplementation).tokensReceived(
_operator, _from, _to, _amount, _data, _operatorData);
} else if (_preventLocking) {
require(isRegularAddress(_to), "Cannot send to contract without ERC777TokensRecipient");
}
}
/// @notice Helper function that checks for ERC777TokensSender on the sender and calls it.
/// May throw according to `_preventLocking`
/// @param _from The address holding the tokens being sent
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be sent
/// @param _data Data generated by the user to be passed to the recipient
/// @param _operatorData Data generated by the operator to be passed to the recipient
/// implementing `ERC777TokensSender`.
/// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer
/// functions SHOULD set this parameter to `false`.
function callSender(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _data,
bytes _operatorData
)
internal
{
address senderImplementation = interfaceAddr(_from, "ERC777TokensSender");
if (senderImplementation == 0) { return; }
ERC777TokensSender(senderImplementation).tokensToSend(
_operator, _from, _to, _amount, _data, _operatorData);
}
}
contract ERC777ERC20BaseToken is ERC20Token, ERC777BaseToken {
bool internal mErc20compatible;
mapping(address => mapping(address => uint256)) internal mAllowed;
constructor(
string _name,
string _symbol,
uint256 _granularity,
address[] _defaultOperators
)
internal ERC777BaseToken(_name, _symbol, _granularity, _defaultOperators)
{
mErc20compatible = true;
setInterfaceImplementation("ERC20Token", this);
}
/// @notice This modifier is applied to erc20 obsolete methods that are
/// implemented only to maintain backwards compatibility. When the erc20
/// compatibility is disabled, this methods will fail.
modifier erc20 () {
require(mErc20compatible, "ERC20 is disabled");
_;
}
/// @notice For Backwards compatibility
/// @return The decimls of the token. Forced to 18 in ERC777.
function decimals() public erc20 view returns (uint8) { return uint8(18); }
/// @notice ERC20 backwards compatible transfer.
/// @param _to The address of the recipient
/// @param _amount The number of tokens to be transferred
/// @return `true`, if the transfer can't be done, it should fail.
function transfer(address _to, uint256 _amount) public erc20 returns (bool success) {
doSend(msg.sender, msg.sender, _to, _amount, "", "", false);
return true;
}
/// @notice ERC20 backwards compatible transferFrom.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The number of tokens to be transferred
/// @return `true`, if the transfer can't be done, it should fail.
function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) {
require(_amount <= mAllowed[_from][msg.sender], "Not enough funds allowed");
// Cannot be after doSend because of tokensReceived re-entry
mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount);
doSend(msg.sender, _from, _to, _amount, "", "", false);
return true;
}
/// @notice ERC20 backwards compatible approve.
/// `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf.
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The number of tokens to be approved for transfer
/// @return `true`, if the approve can't be done, it should fail.
function approve(address _spender, uint256 _amount) public erc20 returns (bool success) {
mAllowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/// @notice ERC20 backwards compatible allowance.
/// This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender) public erc20 view returns (uint256 remaining) {
return mAllowed[_owner][_spender];
}
function doSend(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _data,
bytes _operatorData,
bool _preventLocking
)
internal
{
super.doSend(_operator, _from, _to, _amount, _data, _operatorData, _preventLocking);
if (mErc20compatible) { emit Transfer(_from, _to, _amount); }
}
function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _data, bytes _operatorData)
internal
{
super.doBurn(_operator, _tokenHolder, _amount, _data, _operatorData);
if (mErc20compatible) { emit Transfer(_tokenHolder, 0x0, _amount); }
}
}
contract SecurityToken is ERC777ERC20BaseToken {
struct Document {
string uri;
bytes32 documentHash;
}
event ERC20Enabled();
event ERC20Disabled();
address public burnOperator;
mapping (bytes32 => Document) private documents;
constructor(
string _name,
string _symbol,
uint256 _granularity,
address[] _defaultOperators,
address _burnOperator,
uint256 _initialSupply
)
public ERC777ERC20BaseToken(_name, _symbol, _granularity, _defaultOperators)
{
burnOperator = _burnOperator;
doMint(msg.sender, _initialSupply, "");
}
/// @notice Disables the ERC20 interface. This function can only be called
/// by the owner.
function disableERC20() public onlyOwner {
mErc20compatible = false;
setInterfaceImplementation("ERC20Token", 0x0);
emit ERC20Disabled();
}
/// @notice Re enables the ERC20 interface. This function can only be called
/// by the owner.
function enableERC20() public onlyOwner {
mErc20compatible = true;
setInterfaceImplementation("ERC20Token", this);
emit ERC20Enabled();
}
function getDocument(bytes32 _name) external view returns (string, bytes32) {
Document memory document = documents[_name];
return (document.uri, document.documentHash);
}
function setDocument(bytes32 _name, string _uri, bytes32 _documentHash) external onlyOwner {
documents[_name] = Document(_uri, _documentHash);
}
function setBurnOperator(address _burnOperator) public onlyOwner {
burnOperator = _burnOperator;
}
/* -- Mint And Burn Functions (not part of the ERC777 standard, only the Events/tokensReceived call are) -- */
//
/// @notice Generates `_amount` tokens to be assigned to `_tokenHolder`
/// Sample mint function to showcase the use of the `Minted` event and the logic to notify the recipient.
/// @param _tokenHolder The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @param _operatorData Data that will be passed to the recipient as a first transfer
function mint(address _tokenHolder, uint256 _amount, bytes _operatorData) public onlyOwner {
doMint(_tokenHolder, _amount, _operatorData);
}
/// @notice Burns `_amount` tokens from `msg.sender`
/// Silly example of overriding the `burn` function to only let the owner burn its tokens.
/// Do not forget to override the `burn` function in your token contract if you want to prevent users from
/// burning their tokens.
/// @param _amount The quantity of tokens to burn
function burn(uint256 _amount, bytes _data) public onlyOwner {
super.burn(_amount, _data);
}
/// @notice Burns `_amount` tokens from `_tokenHolder` by `_operator`
/// Silly example of overriding the `operatorBurn` function to only let a specific operator burn tokens.
/// Do not forget to override the `operatorBurn` function in your token contract if you want to prevent users from
/// burning their tokens.
/// @param _tokenHolder The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
function operatorBurn(address _tokenHolder, uint256 _amount, bytes _data, bytes _operatorData) public {
require(msg.sender == burnOperator, "Not a burn operator");
super.operatorBurn(_tokenHolder, _amount, _data, _operatorData);
}
function doMint(address _tokenHolder, uint256 _amount, bytes _operatorData) private {
requireMultiple(_amount);
mTotalSupply = mTotalSupply.add(_amount);
mBalances[_tokenHolder] = mBalances[_tokenHolder].add(_amount);
callRecipient(msg.sender, 0x0, _tokenHolder, _amount, "", _operatorData, true);
addWhitelistAddress(_tokenHolder);
emit Minted(msg.sender, _tokenHolder, _amount, _operatorData);
if (mErc20compatible) { emit Transfer(0x0, _tokenHolder, _amount); }
}
} | @notice Burns `_amount` tokens from `_tokenHolder` by `_operator` Silly example of overriding the `operatorBurn` function to only let a specific operator burn tokens. Do not forget to override the `operatorBurn` function in your token contract if you want to prevent users from burning their tokens. @param _tokenHolder The address that will lose the tokens @param _amount The quantity of tokens to burn | function operatorBurn(address _tokenHolder, uint256 _amount, bytes _data, bytes _operatorData) public {
require(msg.sender == burnOperator, "Not a burn operator");
super.operatorBurn(_tokenHolder, _amount, _data, _operatorData);
}
| 12,953,017 | [
1,
38,
321,
87,
1375,
67,
8949,
68,
2430,
628,
1375,
67,
2316,
6064,
68,
635,
1375,
67,
9497,
68,
225,
348,
330,
715,
3454,
434,
19488,
326,
1375,
9497,
38,
321,
68,
445,
358,
1338,
2231,
279,
2923,
3726,
18305,
2430,
18,
225,
2256,
486,
13776,
358,
3849,
326,
1375,
9497,
38,
321,
68,
445,
316,
3433,
1147,
6835,
309,
1846,
2545,
358,
5309,
3677,
628,
225,
18305,
310,
3675,
2430,
18,
225,
389,
2316,
6064,
1021,
1758,
716,
903,
29612,
326,
2430,
225,
389,
8949,
1021,
10457,
434,
2430,
358,
18305,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3726,
38,
321,
12,
2867,
389,
2316,
6064,
16,
2254,
5034,
389,
8949,
16,
1731,
389,
892,
16,
1731,
389,
9497,
751,
13,
1071,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
18305,
5592,
16,
315,
1248,
279,
18305,
3726,
8863,
203,
3639,
2240,
18,
9497,
38,
321,
24899,
2316,
6064,
16,
389,
8949,
16,
389,
892,
16,
389,
9497,
751,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0xdBf9d503028B3d68e343c4096Fd347A20d1e8966/sources/contracts/01_Pack.sol | 27.9% => 2790/10 000
| foundersPack.weedRareChance = 2790; | 727,884 | [
1,
5324,
18,
29,
9,
282,
516,
576,
7235,
20,
19,
2163,
20546,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1392,
414,
4420,
18,
1814,
329,
54,
834,
782,
1359,
273,
576,
7235,
20,
31,
4202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.6.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface ITokensTypeStorage {
function isRegistred(address _address) external view returns(bool);
function getType(address _address) external view returns(bytes32);
function isPermittedAddress(address _address) external view returns(bool);
function owner() external view returns(address);
function addNewTokenType(address _token, string calldata _type) external;
function setTokenTypeAsOwner(address _token, string calldata _type) external;
}
interface IBalancerPool {
function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external;
function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external;
function getCurrentTokens() external view returns (address[] memory tokens);
}
interface IUniswapV2Pair {
function token0() external view returns (address);
function token1() external view returns (address);
}
interface IUniswapV2Router {
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 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 UniswapFactoryInterfaceV1 {
// Create Exchange
function createExchange(address token) external returns (address exchange);
// Get Exchange and Token Info
function getExchange(address token) external view returns (address exchange);
function getToken(address exchange) external view returns (address token);
function getTokenWithId(uint256 tokenId) external view returns (address token);
// Never use
function initializeFactory(address template) external;
}
interface UniswapExchangeInterface {
// Address of ERC20 token sold on this exchange
function tokenAddress() external view returns (address token);
// Address of Uniswap Factory
function factoryAddress() external view returns (address factory);
// Provide Liquidity
function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256);
function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256);
// Get Prices
function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold);
// Trade ETH to ERC20
function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought);
function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns (uint256 eth_sold);
function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256 eth_sold);
// Trade ERC20 to ETH
function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256 eth_bought);
function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256 eth_bought);
function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256 tokens_sold);
function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256 tokens_sold);
// Trade ERC20 to ERC20
function tokenToTokenSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256 tokens_bought);
function tokenToTokenTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_bought);
function tokenToTokenSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_sold);
// Trade ERC20 to Custom Pool
function tokenToExchangeSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256 tokens_bought);
function tokenToExchangeTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_bought);
function tokenToExchangeSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256 tokens_sold);
function tokenToExchangeTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_sold);
// ERC20 comaptibility for liquidity tokens
function name() external view returns(bytes32);
function symbol() external view returns(bytes32);
function decimals() external view returns(uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function allowance(address _owner, address _spender) external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function totalSupply() external view returns (uint256);
// Never use
function setup(address token_addr) external;
}
interface IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount) external view returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount) external view returns (uint256);
function calculateCrossReserveReturn(uint256 _fromReserveBalance, uint32 _fromReserveRatio, uint256 _toReserveBalance, uint32 _toReserveRatio, uint256 _amount) external view returns (uint256);
function calculateFundCost(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) external view returns (uint256);
function calculateLiquidateReturn(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) external view returns (uint256);
}
interface SmartTokenInterface {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function disableTransfers(bool _disable) external;
function issue(address _to, uint256 _amount) external;
function destroy(address _from, uint256 _amount) external;
function owner() external view returns (address);
}
interface IGetBancorData {
function getBancorContractAddresByName(string calldata _name) external view returns (address result);
function getBancorRatioForAssets(IERC20 _from, IERC20 _to, uint256 _amount) external view returns(uint256 result);
function getBancorPathForAssets(IERC20 _from, IERC20 _to) external view returns(address[] memory);
}
interface BancorConverterInterfaceV2 {
function addLiquidity(address _reserveToken, uint256 _amount, uint256 _minReturn) external payable;
function removeLiquidity(address _poolToken, uint256 _amount, uint256 _minReturn) external;
function poolToken(address _reserveToken) external view returns(address);
function connectorTokenCount() external view returns (uint16);
function connectorTokens(uint index) external view returns(IERC20);
}
interface BancorConverterInterfaceV1 {
function addLiquidity(
address[] calldata _reserveTokens,
uint256[] calldata _reserveAmounts,
uint256 _minReturn) external payable;
function removeLiquidity(
uint256 _amount,
address[] calldata _reserveTokens,
uint256[] calldata _reserveMinReturnAmounts) external;
}
interface BancorConverterInterface {
function connectorTokens(uint index) external view returns(IERC20);
function fund(uint256 _amount) external payable;
function liquidate(uint256 _amount) external;
function getConnectorBalance(IERC20 _connectorToken) external view returns (uint256);
function connectorTokenCount() external view returns (uint16);
}
/*
* This contract allow buy/sell pool for Bancor and Uniswap assets
* and provide ratio and addition info for pool assets
*/
/*
* @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 { }
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 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;
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract PoolPortal is Ownable{
using SafeMath for uint256;
uint public version = 4;
IGetBancorData public bancorData;
UniswapFactoryInterfaceV1 public uniswapFactoryV1;
IUniswapV2Router public uniswapV2Router;
// CoTrader platform recognize ETH by this address
IERC20 constant private ETH_TOKEN_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
// Enum
// NOTE: You can add a new type at the end, but do not change this order
enum PortalType { Bancor, Uniswap, Balancer }
// events
event BuyPool(address poolToken, uint256 amount, address trader);
event SellPool(address poolToken, uint256 amount, address trader);
// Contract for handle tokens types
ITokensTypeStorage public tokensTypes;
/**
* @dev contructor
*
* @param _bancorData address of helper contract GetBancorData
* @param _uniswapFactoryV1 address of Uniswap V1 factory contract
* @param _uniswapV2Router address of Uniswap V2 router
* @param _tokensTypes address of the ITokensTypeStorage
*/
constructor(
address _bancorData,
address _uniswapFactoryV1,
address _uniswapV2Router,
address _tokensTypes
)
public
{
bancorData = IGetBancorData(_bancorData);
uniswapFactoryV1 = UniswapFactoryInterfaceV1(_uniswapFactoryV1);
uniswapV2Router = IUniswapV2Router(_uniswapV2Router);
tokensTypes = ITokensTypeStorage(_tokensTypes);
}
/**
* @dev this function provide necessary data for buy a old BNT and UNI v1 pools by input amount
*
* @param _amount amount of pool token (NOTE: amount of ETH for Uniswap)
* @param _type pool type
* @param _poolToken pool token address
*/
function getDataForBuyingPool(IERC20 _poolToken, uint _type, uint256 _amount)
public
view
returns(
address[] memory connectorsAddress,
uint256[] memory connectorsAmount
)
{
// Buy Bancor pool
if(_type == uint(PortalType.Bancor)){
// get Bancor converter
address converterAddress = getBacorConverterAddressByRelay(address(_poolToken), 0);
// get converter as contract
BancorConverterInterface converter = BancorConverterInterface(converterAddress);
uint256 connectorsCount = converter.connectorTokenCount();
// create arrays for data
connectorsAddress = new address[](connectorsCount);
connectorsAmount = new uint256[](connectorsCount);
// push data
for(uint8 i = 0; i < connectorsCount; i++){
// get current connector address
IERC20 currentConnector = converter.connectorTokens(i);
// push address of current connector
connectorsAddress[i] = address(currentConnector);
// push amount for current connector
connectorsAmount[i] = getBancorConnectorsAmountByRelayAmount(
_amount, _poolToken, address(currentConnector));
}
}
// Buy Uniswap pool
else if(_type == uint(PortalType.Uniswap)){
// get token address
address tokenAddress = uniswapFactoryV1.getToken(address(_poolToken));
// get tokens amd approve to exchange
uint256 erc20Amount = getUniswapTokenAmountByETH(tokenAddress, _amount);
// return data
connectorsAddress = new address[](2);
connectorsAmount = new uint256[](2);
connectorsAddress[0] = address(ETH_TOKEN_ADDRESS);
connectorsAddress[1] = tokenAddress;
connectorsAmount[0] = _amount;
connectorsAmount[1] = erc20Amount;
}
else {
revert("Unknown pool type");
}
}
/**
* @dev buy Bancor or Uniswap pool
*
* @param _amount amount of pool token
* @param _type pool type
* @param _poolToken pool token address (NOTE: for Bancor type 2 don't forget extract pool address from container)
* @param _connectorsAddress address of pool connectors (NOTE: for Uniswap ETH should be pass in [0], ERC20 in [1])
* @param _connectorsAmount amount of pool connectors (NOTE: for Uniswap ETH amount should be pass in [0], ERC20 in [1])
* @param _additionalArgs bytes32 array for case if need pass some extra params, can be empty
* @param _additionalData for provide any additional data, if not used just set "0x",
* for Bancor _additionalData[0] should be converterVersion and _additionalData[1] should be converterType
*
*/
function buyPool
(
uint256 _amount,
uint _type,
address _poolToken,
address[] calldata _connectorsAddress,
uint256[] calldata _connectorsAmount,
bytes32[] calldata _additionalArgs,
bytes calldata _additionalData
)
external
payable
returns(uint256 poolAmountReceive, uint256[] memory connectorsSpended)
{
// Buy Bancor pool
if(_type == uint(PortalType.Bancor)){
(poolAmountReceive) = buyBancorPool(
_amount,
_poolToken,
_connectorsAddress,
_connectorsAmount,
_additionalArgs,
_additionalData
);
}
// Buy Uniswap pool
else if (_type == uint(PortalType.Uniswap)){
(poolAmountReceive) = buyUniswapPool(
_amount,
_poolToken,
_connectorsAddress,
_connectorsAmount,
_additionalArgs,
_additionalData
);
}
// Buy Balancer pool
else if (_type == uint(PortalType.Balancer)){
(poolAmountReceive) = buyBalancerPool(
_amount,
_poolToken,
_connectorsAddress,
_connectorsAmount
);
}
else{
// unknown portal type
revert("Unknown portal type");
}
// transfer pool token to fund
IERC20(_poolToken).transfer(msg.sender, poolAmountReceive);
// transfer connectors remains to fund
// and calculate how much connectors was spended (current - remains)
connectorsSpended = _transferPoolConnectorsRemains(
_connectorsAddress,
_connectorsAmount);
// trigger event
emit BuyPool(address(_poolToken), poolAmountReceive, msg.sender);
}
/**
* @dev helper for buying Bancor pool token by a certain converter version and converter type
* Bancor has 3 cases for different converter version and type
*/
function buyBancorPool(
uint256 _amount,
address _poolToken,
address[] calldata _connectorsAddress,
uint256[] calldata _connectorsAmount,
bytes32[] calldata _additionalArgs,
bytes calldata _additionalData
)
private
returns(uint256 poolAmountReceive)
{
// get Bancor converter address by pool token and pool type
address converterAddress = getBacorConverterAddressByRelay(
_poolToken,
uint256(_additionalArgs[1])
);
// transfer from sender and approve to converter
// for detect if there are ETH in connectors or not we use etherAmount
uint256 etherAmount = _approvePoolConnectors(
_connectorsAddress,
_connectorsAmount,
converterAddress
);
// Buy Bancor pool according converter version and type
// encode and compare converter version
if(uint256(_additionalArgs[0]) >= 28) {
// encode and compare converter type
if(uint256(_additionalArgs[1]) == 2) {
// buy Bancor v2 case
_buyBancorPoolV2(
converterAddress,
etherAmount,
_connectorsAddress,
_connectorsAmount,
_additionalData
);
} else{
// buy Bancor v1 case
_buyBancorPoolV1(
converterAddress,
etherAmount,
_connectorsAddress,
_connectorsAmount,
_additionalData
);
}
}
else {
// buy Bancor old v0 case
_buyBancorPoolOldV(
converterAddress,
etherAmount,
_amount
);
}
// get recieved pool amount
poolAmountReceive = IERC20(_poolToken).balanceOf(address(this));
// make sure we recieved pool
require(poolAmountReceive > 0, "ERR BNT pool received 0");
// set token type for this asset
tokensTypes.addNewTokenType(_poolToken, "BANCOR_ASSET");
}
/**
* @dev helper for buy pool in Bancor network for old converter version
*/
function _buyBancorPoolOldV(
address converterAddress,
uint256 etherAmount,
uint256 _amount)
private
{
// get converter as contract
BancorConverterInterface converter = BancorConverterInterface(converterAddress);
// buy relay from converter
if(etherAmount > 0){
// payable
converter.fund.value(etherAmount)(_amount);
}else{
// non payable
converter.fund(_amount);
}
}
/**
* @dev helper for buy pool in Bancor network for new converter type 1
*/
function _buyBancorPoolV1(
address converterAddress,
uint256 etherAmount,
address[] calldata _connectorsAddress,
uint256[] calldata _connectorsAmount,
bytes memory _additionalData
)
private
{
BancorConverterInterfaceV1 converter = BancorConverterInterfaceV1(converterAddress);
// get additional data
(uint256 minReturn) = abi.decode(_additionalData, (uint256));
// buy relay from converter
if(etherAmount > 0){
// payable
converter.addLiquidity.value(etherAmount)(_connectorsAddress, _connectorsAmount, minReturn);
}else{
// non payable
converter.addLiquidity(_connectorsAddress, _connectorsAmount, minReturn);
}
}
/**
* @dev helper for buy pool in Bancor network for new converter type 2
*/
function _buyBancorPoolV2(
address converterAddress,
uint256 etherAmount,
address[] calldata _connectorsAddress,
uint256[] calldata _connectorsAmount,
bytes memory _additionalData
)
private
{
// get converter as contract
BancorConverterInterfaceV2 converter = BancorConverterInterfaceV2(converterAddress);
// get additional data
(uint256 minReturn) = abi.decode(_additionalData, (uint256));
// buy relay from converter
if(etherAmount > 0){
// payable
converter.addLiquidity.value(etherAmount)(_connectorsAddress[0], _connectorsAmount[0], minReturn);
}else{
// non payable
converter.addLiquidity(_connectorsAddress[0], _connectorsAmount[0], minReturn);
}
}
/**
* @dev helper for buying Uniswap v1 or v2 pool
*/
function buyUniswapPool(
uint256 _amount,
address _poolToken,
address[] calldata _connectorsAddress,
uint256[] calldata _connectorsAmount,
bytes32[] calldata _additionalArgs,
bytes calldata _additionalData
)
private
returns(uint256 poolAmountReceive)
{
// define spender dependse of UNI pool version
address spender = uint256(_additionalArgs[0]) == 1
? _poolToken
: address(uniswapV2Router);
// approve pool tokens to Uni pool exchange
_approvePoolConnectors(
_connectorsAddress,
_connectorsAmount,
spender);
// Buy Uni pool dependse of version
if(uint256(_additionalArgs[0]) == 1){
_buyUniswapPoolV1(
_poolToken,
_connectorsAddress[1], // connector ERC20 token address
_connectorsAmount[1], // connector ERC20 token amount
_amount);
}else{
_buyUniswapPoolV2(
_poolToken,
_connectorsAddress,
_connectorsAmount,
_additionalData
);
}
// get pool amount
poolAmountReceive = IERC20(_poolToken).balanceOf(address(this));
// check if we recieved pool token
require(poolAmountReceive > 0, "ERR UNI pool received 0");
}
/**
* @dev helper for buy pool in Uniswap network v1
*
* @param _poolToken address of Uniswap exchange
* @param _tokenAddress address of ERC20 conenctor
* @param _erc20Amount amount of ERC20 connector
* @param _ethAmount ETH amount (in wei)
*/
function _buyUniswapPoolV1(
address _poolToken,
address _tokenAddress,
uint256 _erc20Amount,
uint256 _ethAmount
)
private
{
require(_ethAmount == msg.value, "Not enough ETH");
// get exchange contract
UniswapExchangeInterface exchange = UniswapExchangeInterface(_poolToken);
// set deadline
uint256 deadline = now + 15 minutes;
// buy pool
exchange.addLiquidity.value(_ethAmount)(
1,
_erc20Amount,
deadline
);
// Set token type
tokensTypes.addNewTokenType(_poolToken, "UNISWAP_POOL");
}
/**
* @dev helper for buy pool in Uniswap network v2
*/
function _buyUniswapPoolV2(
address _poolToken,
address[] calldata _connectorsAddress,
uint256[] calldata _connectorsAmount,
bytes calldata _additionalData
)
private
{
// set deadline
uint256 deadline = now + 15 minutes;
// get additional data
(uint256 amountAMinReturn,
uint256 amountBMinReturn) = abi.decode(_additionalData, (uint256, uint256));
// Buy UNI V2 pool
// ETH connector case
if(_connectorsAddress[0] == address(ETH_TOKEN_ADDRESS)){
uniswapV2Router.addLiquidityETH.value(_connectorsAmount[0])(
_connectorsAddress[1],
_connectorsAmount[1],
amountBMinReturn,
amountAMinReturn,
address(this),
deadline
);
}
// ERC20 connector case
else{
uniswapV2Router.addLiquidity(
_connectorsAddress[0],
_connectorsAddress[1],
_connectorsAmount[0],
_connectorsAmount[1],
amountAMinReturn,
amountBMinReturn,
address(this),
deadline
);
}
// Set token type
tokensTypes.addNewTokenType(_poolToken, "UNISWAP_POOL_V2");
}
/**
* @dev helper for buying Balancer pool
*/
function buyBalancerPool(
uint256 _amount,
address _poolToken,
address[] calldata _connectorsAddress,
uint256[] calldata _connectorsAmount
)
private
returns(uint256 poolAmountReceive)
{
// approve pool tokens to Balancer pool exchange
_approvePoolConnectors(
_connectorsAddress,
_connectorsAmount,
_poolToken);
// buy pool
IBalancerPool(_poolToken).joinPool(_amount, _connectorsAmount);
// get balance
poolAmountReceive = IERC20(_poolToken).balanceOf(address(this));
// check
require(poolAmountReceive > 0, "ERR BALANCER pool received 0");
// update type
tokensTypes.addNewTokenType(_poolToken, "BALANCER_POOL");
}
/**
* @dev helper for buying BNT or UNI pools, approve connectors from msg.sender to spender address
* return ETH amount if connectorsAddress contains ETH address
*/
function _approvePoolConnectors(
address[] memory connectorsAddress,
uint256[] memory connectorsAmount,
address spender
)
private
returns(uint256 etherAmount)
{
// approve from portal to spender
for(uint8 i = 0; i < connectorsAddress.length; i++){
if(connectorsAddress[i] != address(ETH_TOKEN_ADDRESS)){
// transfer from msg.sender and approve to
_transferFromSenderAndApproveTo(
IERC20(connectorsAddress[i]),
connectorsAmount[i],
spender);
}else{
etherAmount = connectorsAmount[i];
}
}
}
/**
* @dev helper for buying BNT or UNI pools, transfer ERC20 tokens and ETH remains after bying pool,
* if the balance is positive on this contract, and calculate how many assets was spent.
*/
function _transferPoolConnectorsRemains(
address[] memory connectorsAddress,
uint256[] memory currentConnectorsAmount
)
private
returns (uint256[] memory connectorsSpended)
{
// set length for connectorsSpended
connectorsSpended = new uint256[](currentConnectorsAmount.length);
// transfer connectors back to fund if some amount remains
uint256 remains = 0;
for(uint8 i = 0; i < connectorsAddress.length; i++){
// ERC20 case
if(connectorsAddress[i] != address(ETH_TOKEN_ADDRESS)){
// check balance
remains = IERC20(connectorsAddress[i]).balanceOf(address(this));
// transfer ERC20
if(remains > 0)
IERC20(connectorsAddress[i]).transfer(msg.sender, remains);
}
// ETH case
else {
remains = address(this).balance;
// transfer ETH
if(remains > 0)
(msg.sender).transfer(remains);
}
// calculate how many assets was spent
connectorsSpended[i] = currentConnectorsAmount[i].sub(remains);
}
}
/**
* @dev return token ration in ETH in Uniswap network
*
* @param _token address of ERC20 token
* @param _amount ETH amount
*/
function getUniswapTokenAmountByETH(address _token, uint256 _amount)
public
view
returns(uint256)
{
UniswapExchangeInterface exchange = UniswapExchangeInterface(
uniswapFactoryV1.getExchange(_token));
return exchange.getTokenToEthOutputPrice(_amount);
}
/**
* @dev sell Bancor or Uniswap pool
*
* @param _amount amount of pool token
* @param _type pool type
* @param _poolToken pool token address
* @param _additionalArgs bytes32 array for case if need pass some extra params, can be empty
* @param _additionalData for provide any additional data, if not used just set "0x"
*/
function sellPool
(
uint256 _amount,
uint _type,
IERC20 _poolToken,
bytes32[] calldata _additionalArgs,
bytes calldata _additionalData
)
external
returns(
address[] memory connectorsAddress,
uint256[] memory connectorsAmount
)
{
// sell Bancor Pool
if(_type == uint(PortalType.Bancor)){
(connectorsAddress, connectorsAmount) = sellBancorPool(
_amount,
_poolToken,
_additionalArgs,
_additionalData);
}
// sell Uniswap pool
else if (_type == uint(PortalType.Uniswap)){
(connectorsAddress, connectorsAmount) = sellUniswapPool(
_poolToken,
_amount,
_additionalArgs,
_additionalData);
}
// sell Balancer pool
else if (_type == uint(PortalType.Balancer)){
(connectorsAddress, connectorsAmount) = sellBalancerPool(
_amount,
_poolToken,
_additionalData);
}
else{
revert("Unknown portal type");
}
emit SellPool(address(_poolToken), _amount, msg.sender);
}
/**
* @dev helper for sell pool in Bancor network dependse of converter version and type
*/
function sellBancorPool(
uint256 _amount,
IERC20 _poolToken,
bytes32[] calldata _additionalArgs,
bytes calldata _additionalData
)
private
returns(
address[] memory connectorsAddress,
uint256[] memory connectorsAmount
)
{
// transfer pool from fund
_poolToken.transferFrom(msg.sender, address(this), _amount);
// get Bancor converter version and type
uint256 bancorPoolVersion = uint256(_additionalArgs[0]);
uint256 bancorConverterType = uint256(_additionalArgs[1]);
// sell pool according converter version and type
if(bancorPoolVersion >= 28){
// sell new Bancor v2 pool
if(bancorConverterType == 2){
(connectorsAddress) = sellPoolViaBancorV2(
_poolToken,
_amount,
_additionalData
);
}
// sell new Bancor v1 pool
else{
(connectorsAddress) = sellPoolViaBancorV1(_poolToken, _amount, _additionalData);
}
}
// sell old Bancor pool
else{
(connectorsAddress) = sellPoolViaBancorOldV(_poolToken, _amount);
}
// transfer pool connectors back to fund
connectorsAmount = transferConnectorsToSender(connectorsAddress);
}
/**
* @dev helper for sell pool in Bancor network for old converter version
*
* @param _poolToken address of bancor relay
* @param _amount amount of bancor relay
*/
function sellPoolViaBancorOldV(IERC20 _poolToken, uint256 _amount)
private
returns(address[] memory connectorsAddress)
{
// get Bancor Converter instance
address converterAddress = getBacorConverterAddressByRelay(address(_poolToken), 0);
BancorConverterInterface converter = BancorConverterInterface(converterAddress);
// liquidate relay
converter.liquidate(_amount);
// return connectors addresses
uint256 connectorsCount = converter.connectorTokenCount();
connectorsAddress = new address[](connectorsCount);
for(uint8 i = 0; i<connectorsCount; i++){
connectorsAddress[i] = address(converter.connectorTokens(i));
}
}
/**
* @dev helper for sell pool in Bancor network converter type v1
*/
function sellPoolViaBancorV1(
IERC20 _poolToken,
uint256 _amount,
bytes memory _additionalData
)
private
returns(address[] memory connectorsAddress)
{
// get Bancor Converter address
address converterAddress = getBacorConverterAddressByRelay(address(_poolToken), 1);
// get min returns
uint256[] memory reserveMinReturnAmounts;
// get connetor tokens data for remove liquidity
(connectorsAddress, reserveMinReturnAmounts) = abi.decode(_additionalData, (address[], uint256[]));
// get coneverter v1 contract
BancorConverterInterfaceV1 converter = BancorConverterInterfaceV1(converterAddress);
// remove liquidity (v1)
converter.removeLiquidity(_amount, connectorsAddress, reserveMinReturnAmounts);
}
/**
* @dev helper for sell pool in Bancor network converter type v2
*/
function sellPoolViaBancorV2(
IERC20 _poolToken,
uint256 _amount,
bytes calldata _additionalData
)
private
returns(address[] memory connectorsAddress)
{
// get Bancor Converter address
address converterAddress = getBacorConverterAddressByRelay(address(_poolToken), 2);
// get converter v2 contract
BancorConverterInterfaceV2 converter = BancorConverterInterfaceV2(converterAddress);
// get additional data
uint256 minReturn;
// get pool connectors
(connectorsAddress, minReturn) = abi.decode(_additionalData, (address[], uint256));
// remove liquidity (v2)
converter.removeLiquidity(address(_poolToken), _amount, minReturn);
}
/**
* @dev helper for sell pool in Uniswap network for v1 and v2
*/
function sellUniswapPool(
IERC20 _poolToken,
uint256 _amount,
bytes32[] calldata _additionalArgs,
bytes calldata _additionalData
)
private
returns(
address[] memory connectorsAddress,
uint256[] memory connectorsAmount
)
{
// define spender dependse of UNI pool version
address spender = uint256(_additionalArgs[0]) == 1
? address(_poolToken)
: address(uniswapV2Router);
// approve pool token
_transferFromSenderAndApproveTo(_poolToken, _amount, spender);
// sell Uni v1 or v2 pool
if(uint256(_additionalArgs[0]) == 1){
(connectorsAddress) = sellPoolViaUniswapV1(_poolToken, _amount);
}else{
(connectorsAddress) = sellPoolViaUniswapV2(_amount, _additionalData);
}
// transfer pool connectors back to fund
connectorsAmount = transferConnectorsToSender(connectorsAddress);
}
/**
* @dev helper for sell pool in Uniswap network v1
*/
function sellPoolViaUniswapV1(
IERC20 _poolToken,
uint256 _amount
)
private
returns(address[] memory connectorsAddress)
{
// get token by pool token
address tokenAddress = uniswapFactoryV1.getToken(address(_poolToken));
// check if such a pool exist
if(tokenAddress != address(0x0000000000000000000000000000000000000000)){
// get UNI exchane
UniswapExchangeInterface exchange = UniswapExchangeInterface(address(_poolToken));
// get min returns
(uint256 minEthAmount,
uint256 minErcAmount) = getUniswapConnectorsAmountByPoolAmount(_amount, address(_poolToken));
// set deadline
uint256 deadline = now + 15 minutes;
// liquidate
exchange.removeLiquidity(
_amount,
minEthAmount,
minErcAmount,
deadline);
// return data
connectorsAddress = new address[](2);
connectorsAddress[0] = address(ETH_TOKEN_ADDRESS);
connectorsAddress[1] = tokenAddress;
}
else{
revert("Not exist UNI v1 pool");
}
}
/**
* @dev helper for sell pool in Uniswap network v2
*/
function sellPoolViaUniswapV2(
uint256 _amount,
bytes calldata _additionalData
)
private
returns(address[] memory connectorsAddress)
{
// get additional data
uint256 minReturnA;
uint256 minReturnB;
// get connectors and min return from bytes
(connectorsAddress,
minReturnA,
minReturnB) = abi.decode(_additionalData, (address[], uint256, uint256));
// get deadline
uint256 deadline = now + 15 minutes;
// sell pool with include eth connector
if(connectorsAddress[0] == address(ETH_TOKEN_ADDRESS)){
uniswapV2Router.removeLiquidityETH(
connectorsAddress[1],
_amount,
minReturnB,
minReturnA,
address(this),
deadline
);
}
// sell pool only with erc20 connectors
else{
uniswapV2Router.removeLiquidity(
connectorsAddress[0],
connectorsAddress[1],
_amount,
minReturnA,
minReturnB,
address(this),
deadline
);
}
}
/**
* @dev helper for sell Balancer pool
*/
function sellBalancerPool(
uint256 _amount,
IERC20 _poolToken,
bytes calldata _additionalData
)
private
returns(
address[] memory connectorsAddress,
uint256[] memory connectorsAmount
)
{
// get additional data
uint256[] memory minConnectorsAmount;
(connectorsAddress,
minConnectorsAmount) = abi.decode(_additionalData, (address[], uint256[]));
// approve pool
_transferFromSenderAndApproveTo(
_poolToken,
_amount,
address(_poolToken));
// sell pool
IBalancerPool(address(_poolToken)).exitPool(_amount, minConnectorsAmount);
// transfer connectors back to fund
connectorsAmount = transferConnectorsToSender(connectorsAddress);
}
/**
* @dev helper for sell Bancor and Uniswap pools
* transfer pool connectors from sold pool back to sender
* return array with amount of recieved connectors
*/
function transferConnectorsToSender(address[] memory connectorsAddress)
private
returns(uint256[] memory connectorsAmount)
{
// define connectors amount length
connectorsAmount = new uint256[](connectorsAddress.length);
uint256 received = 0;
// transfer connectors back to fund
for(uint8 i = 0; i < connectorsAddress.length; i++){
// ETH case
if(connectorsAddress[i] == address(ETH_TOKEN_ADDRESS)){
// update ETH data
received = address(this).balance;
connectorsAmount[i] = received;
// tarnsfer ETH
if(received > 0)
payable(msg.sender).transfer(received);
}
// ERC20 case
else{
// update ERC20 data
received = IERC20(connectorsAddress[i]).balanceOf(address(this));
connectorsAmount[i] = received;
// transfer ERC20
if(received > 0)
IERC20(connectorsAddress[i]).transfer(msg.sender, received);
}
}
}
/**
* @dev helper for get bancor converter by bancor relay addrses
*
* @param _relay address of bancor relay
* @param _poolType bancor pool type
*/
function getBacorConverterAddressByRelay(address _relay, uint256 _poolType)
public
view
returns(address converter)
{
if(_poolType == 2){
address smartTokenContainer = SmartTokenInterface(_relay).owner();
converter = SmartTokenInterface(smartTokenContainer).owner();
}else{
converter = SmartTokenInterface(_relay).owner();
}
}
/**
* @dev return ERC20 address from Uniswap exchange address
*
* @param _exchange address of uniswap exchane
*/
function getTokenByUniswapExchange(address _exchange)
external
view
returns(address)
{
return uniswapFactoryV1.getToken(_exchange);
}
/**
* @dev helper for get amounts for both Uniswap connectors for input amount of pool
*
* @param _amount relay amount
* @param _exchange address of uniswap exchane
*/
function getUniswapConnectorsAmountByPoolAmount(
uint256 _amount,
address _exchange
)
public
view
returns(uint256 ethAmount, uint256 ercAmount)
{
IERC20 token = IERC20(uniswapFactoryV1.getToken(_exchange));
// total_liquidity exchange.totalSupply
uint256 totalLiquidity = UniswapExchangeInterface(_exchange).totalSupply();
// ethAmount = amount * exchane.eth.balance / total_liquidity
ethAmount = _amount.mul(_exchange.balance).div(totalLiquidity);
// ercAmount = amount * token.balanceOf(exchane) / total_liquidity
ercAmount = _amount.mul(token.balanceOf(_exchange)).div(totalLiquidity);
}
/**
* @dev helper for get amounts for both Uniswap connectors for input amount of pool
* for Uniswap version 2
*
* @param _amount pool amount
* @param _exchange address of uniswap exchane
*/
function getUniswapV2ConnectorsAmountByPoolAmount(
uint256 _amount,
address _exchange
)
public
view
returns(
uint256 tokenAmountOne,
uint256 tokenAmountTwo,
address tokenAddressOne,
address tokenAddressTwo
)
{
tokenAddressOne = IUniswapV2Pair(_exchange).token0();
tokenAddressTwo = IUniswapV2Pair(_exchange).token1();
// total_liquidity exchange.totalSupply
uint256 totalLiquidity = IERC20(_exchange).totalSupply();
// ethAmount = amount * exchane.eth.balance / total_liquidity
tokenAmountOne = _amount.mul(IERC20(tokenAddressOne).balanceOf(_exchange)).div(totalLiquidity);
// ercAmount = amount * token.balanceOf(exchane) / total_liquidity
tokenAmountTwo = _amount.mul(IERC20(tokenAddressTwo).balanceOf(_exchange)).div(totalLiquidity);
}
/**
* @dev helper for get amounts all Balancer connectors for input amount of pool
* for Balancer
*
* step 1 get all tokens
* step 2 get user amount from each token by a user pool share
*
* @param _amount pool amount
* @param _pool address of balancer pool
*/
function getBalancerConnectorsAmountByPoolAmount(
uint256 _amount,
address _pool
)
public
view
returns(
address[] memory tokens,
uint256[] memory tokensAmount
)
{
IBalancerPool balancerPool = IBalancerPool(_pool);
// get all pool tokens
tokens = balancerPool.getCurrentTokens();
// set tokens amount length
tokensAmount = new uint256[](tokens.length);
// get total pool shares
uint256 totalShares = IERC20(_pool).totalSupply();
// calculate all tokens from the pool
for(uint i = 0; i < tokens.length; i++){
// get a certain total token amount in pool
uint256 totalTokenAmount = IERC20(tokens[i]).balanceOf(_pool);
// get a certain pool share (_amount) from a certain token amount in pool
tokensAmount[i] = totalTokenAmount.mul(_amount).div(totalShares);
}
}
/**
* @dev helper for get value in pool for a certain connector address
*
* @param _amount relay amount
* @param _relay address of bancor relay
* @param _connector address of relay connector
*/
function getBancorConnectorsAmountByRelayAmount
(
uint256 _amount,
IERC20 _relay,
address _connector
)
public
view
returns(uint256 connectorAmount)
{
// get converter contract
BancorConverterInterface converter = BancorConverterInterface(
SmartTokenInterface(address(_relay)).owner());
// get connector balance
uint256 connectorBalance = converter.getConnectorBalance(IERC20(_connector));
// get bancor formula contract
IBancorFormula bancorFormula = IBancorFormula(
bancorData.getBancorContractAddresByName("BancorFormula"));
// calculate input
connectorAmount = bancorFormula.calculateFundCost(
_relay.totalSupply(),
connectorBalance,
1000000,
_amount);
}
/**
* @dev helper for get Bancor ERC20 connectors addresses for old Bancor version
*
* @param _relay address of bancor relay
*/
function getBancorConnectorsByRelay(address _relay)
public
view
returns(
IERC20[] memory connectors
)
{
address converterAddress = getBacorConverterAddressByRelay(_relay, 0);
BancorConverterInterface converter = BancorConverterInterface(converterAddress);
uint256 connectorTokenCount = converter.connectorTokenCount();
connectors = new IERC20[](connectorTokenCount);
for(uint8 i; i < connectorTokenCount; i++){
connectors[i] = converter.connectorTokens(i);
}
}
/**
* @dev helper for get ratio between assets in bancor newtork
*
* @param _from token or relay address
* @param _to token or relay address
* @param _amount amount from
*/
function getBancorRatio(address _from, address _to, uint256 _amount)
external
view
returns(uint256)
{
// return Bancor ratio
return bancorData.getBancorRatioForAssets(IERC20(_from), IERC20(_to), _amount);
}
// owner of portal can change getBancorData helper, for case if Bancor do some major updates
function setNewGetBancorData(address _bancorData) public onlyOwner {
bancorData = IGetBancorData(_bancorData);
}
/**
* @dev Transfers tokens to this contract and approves them to another address
*
* @param _source Token to transfer and approve
* @param _sourceAmount The amount to transfer and approve (in _source token)
* @param _to Address to approve to
*/
function _transferFromSenderAndApproveTo(IERC20 _source, uint256 _sourceAmount, address _to) private {
require(_source.transferFrom(msg.sender, address(this), _sourceAmount));
// reset previous approve (some ERC20 not allow do new approve if already approved)
_source.approve(_to, 0);
// approve
_source.approve(_to, _sourceAmount);
}
// fallback payable function to receive ether from other contract addresses
fallback() external payable {}
} | * @dev helper for buying BNT or UNI pools, approve connectors from msg.sender to spender address return ETH amount if connectorsAddress contains ETH address/ approve from portal to spender transfer from msg.sender and approve to | function _approvePoolConnectors(
address[] memory connectorsAddress,
uint256[] memory connectorsAmount,
address spender
)
private
returns(uint256 etherAmount)
{
for(uint8 i = 0; i < connectorsAddress.length; i++){
if(connectorsAddress[i] != address(ETH_TOKEN_ADDRESS)){
_transferFromSenderAndApproveTo(
IERC20(connectorsAddress[i]),
connectorsAmount[i],
spender);
etherAmount = connectorsAmount[i];
}
}
}
| 6,512,839 | [
1,
4759,
364,
30143,
310,
605,
1784,
578,
19462,
16000,
16,
6617,
537,
28473,
628,
1234,
18,
15330,
358,
17571,
264,
1758,
327,
512,
2455,
3844,
309,
28473,
1887,
1914,
512,
2455,
1758,
19,
6617,
537,
628,
11899,
358,
17571,
264,
7412,
628,
1234,
18,
15330,
471,
6617,
537,
358,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
12908,
537,
2864,
7487,
87,
12,
203,
565,
1758,
8526,
3778,
28473,
1887,
16,
203,
565,
2254,
5034,
8526,
3778,
28473,
6275,
16,
203,
565,
1758,
17571,
264,
203,
225,
262,
203,
565,
3238,
203,
565,
1135,
12,
11890,
5034,
225,
2437,
6275,
13,
203,
225,
288,
203,
565,
364,
12,
11890,
28,
277,
273,
374,
31,
277,
411,
28473,
1887,
18,
2469,
31,
277,
27245,
95,
203,
1377,
309,
12,
4646,
18886,
1887,
63,
77,
65,
480,
1758,
12,
1584,
44,
67,
8412,
67,
15140,
3719,
95,
203,
3639,
389,
13866,
1265,
12021,
1876,
12053,
537,
774,
12,
203,
1850,
467,
654,
39,
3462,
12,
4646,
18886,
1887,
63,
77,
65,
3631,
203,
1850,
28473,
6275,
63,
77,
6487,
203,
1850,
17571,
264,
1769,
203,
3639,
225,
2437,
6275,
273,
28473,
6275,
63,
77,
15533,
203,
1377,
289,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xc0dF98dF13BD5FD923625be48D6e293707572Bdc/sources/Eligible.sol | Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount | contract Eligible is ERC20, Ownable {
uint256 public maxBuyAmount;
uint256 public maxSellAmount;
uint256 public maxWalletAmount;
IDexRouter public dexRouter;
address public lpPair;
bool private swapping;
uint256 public swapTokensAtAmount;
address operationsAddress;
address devAddress;
uint256 public blockForPenaltyEnd;
mapping (address => bool) public boughtEarly;
uint256 public botsCaught;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyOperationsFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public buyBurnFee;
uint256 public sellTotalFees;
uint256 public sellOperationsFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public sellBurnFee;
uint256 public tokensForOperations;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
uint256 public tokensForBurn;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
mapping (address => bool) public automatedMarketMakerPairs;
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event EnabledTrading();
event RemovedLimits();
event ExcludeFromFees(address indexed account, bool isExcluded);
event UpdatedMaxBuyAmount(uint256 newAmount);
event UpdatedMaxSellAmount(uint256 newAmount);
event UpdatedMaxWalletAmount(uint256 newAmount);
event UpdatedOperationsAddress(address indexed newWallet);
event MaxTransactionExclusion(address _address, bool excluded);
event BuyBackTriggered(uint256 amount);
event OwnerForcedSwapBack(uint256 timestamp);
event CaughtEarlyBuyer(address sniper);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event TransferForeignToken(address token, uint256 amount);
constructor() ERC20(unicode"Eligible", unicode"ELG") {
address newOwner = msg.sender;
IDexRouter _dexRouter = IDexRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
dexRouter = _dexRouter;
lpPair = IDexFactory(_dexRouter.factory()).createPair(address(this), _dexRouter.WETH());
_excludeFromMaxTransaction(address(lpPair), true);
_setAutomatedMarketMakerPair(address(lpPair), true);
uint256 totalSupply = 100000 * 1e18;
maxBuyAmount = totalSupply * 5 / 1000;
maxSellAmount = totalSupply * 5 / 1000;
maxWalletAmount = totalSupply * 5 / 1000;
swapTokensAtAmount = totalSupply * 3 / 1000;
buyOperationsFee = 20;
buyLiquidityFee = 8;
buyDevFee = 1;
buyBurnFee = 1;
buyTotalFees = buyOperationsFee + buyLiquidityFee + buyDevFee + buyBurnFee;
sellOperationsFee = 23;
sellLiquidityFee = 10;
sellDevFee = 1;
sellBurnFee = 1;
sellTotalFees = sellOperationsFee + sellLiquidityFee + sellDevFee + sellBurnFee;
_excludeFromMaxTransaction(newOwner, true);
_excludeFromMaxTransaction(address(this), true);
_excludeFromMaxTransaction(address(0xdead), true);
excludeFromFees(newOwner, true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
operationsAddress = address(newOwner);
devAddress = address(newOwner);
_createInitialSupply(newOwner, totalSupply);
transferOwnership(newOwner);
}
receive() external payable {}
function enableTrading(uint256 deadBlocks) external onlyOwner {
require(!tradingActive, "Cannot reenable trading");
tradingActive = true;
swapEnabled = true;
tradingActiveBlock = block.number;
blockForPenaltyEnd = tradingActiveBlock + deadBlocks;
emit EnabledTrading();
}
function removeLimits() external onlyOwner {
limitsInEffect = false;
transferDelayEnabled = false;
emit RemovedLimits();
}
function manageBoughtEarly(address wallet, bool flag) external onlyOwner {
boughtEarly[wallet] = flag;
}
function massManageBoughtEarly(address[] calldata wallets, bool flag) external onlyOwner {
for(uint256 i = 0; i < wallets.length; i++){
boughtEarly[wallets[i]] = flag;
}
}
function massManageBoughtEarly(address[] calldata wallets, bool flag) external onlyOwner {
for(uint256 i = 0; i < wallets.length; i++){
boughtEarly[wallets[i]] = flag;
}
}
function disableTransferDelay() external onlyOwner {
transferDelayEnabled = false;
}
function updateMaxBuyAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 2 / 1000)/1e18, "Cannot set max buy amount lower than 0.2%");
maxBuyAmount = newNum * (10**18);
emit UpdatedMaxBuyAmount(maxBuyAmount);
}
function updateMaxSellAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 2 / 1000)/1e18, "Cannot set max sell amount lower than 0.2%");
maxSellAmount = newNum * (10**18);
emit UpdatedMaxSellAmount(maxSellAmount);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 3 / 1000)/1e18, "Cannot set max wallet amount lower than 0.3%");
maxWalletAmount = newNum * (10**18);
emit UpdatedMaxWalletAmount(maxWalletAmount);
}
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner {
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 1 / 1000, "Swap amount cannot be higher than 0.1% total supply.");
swapTokensAtAmount = newAmount;
}
function _excludeFromMaxTransaction(address updAds, bool isExcluded) private {
_isExcludedMaxTransactionAmount[updAds] = isExcluded;
emit MaxTransactionExclusion(updAds, isExcluded);
}
function excludeFromMaxTransaction(address updAds, bool isEx) external onlyOwner {
if(!isEx){
require(updAds != lpPair, "Cannot remove uniswap pair from max txn");
}
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function excludeFromMaxTransaction(address updAds, bool isEx) external onlyOwner {
if(!isEx){
require(updAds != lpPair, "Cannot remove uniswap pair from max txn");
}
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function setAutomatedMarketMakerPair(address pair, bool value) external onlyOwner {
require(pair != lpPair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
emit SetAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
_excludeFromMaxTransaction(pair, value);
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateBuyFees(uint256 _operationsFee, uint256 _liquidityFee, uint256 _devFee, uint256 _burnFee) external onlyOwner {
buyOperationsFee = _operationsFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyBurnFee = _burnFee;
buyTotalFees = buyOperationsFee + buyLiquidityFee + buyDevFee + buyBurnFee;
require(buyTotalFees <= 30, "Must keep fees at 30% or less");
}
function updateSellFees(uint256 _operationsFee, uint256 _liquidityFee, uint256 _devFee, uint256 _burnFee) external onlyOwner {
sellOperationsFee = _operationsFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellBurnFee = _burnFee;
sellTotalFees = sellOperationsFee + sellLiquidityFee + sellDevFee + sellBurnFee;
require(sellTotalFees <= 48, "Must keep fees at 48% or less");
}
function returnToNormalTax() external onlyOwner {
sellOperationsFee = 3;
sellLiquidityFee = 0;
sellDevFee = 0;
sellBurnFee = 0;
sellTotalFees = sellOperationsFee + sellLiquidityFee + sellDevFee + sellBurnFee;
require(sellTotalFees <= 30, "Must keep fees at 30% or less");
buyOperationsFee = 3;
buyLiquidityFee = 0;
buyDevFee = 0;
buyBurnFee = 0;
buyTotalFees = buyOperationsFee + buyLiquidityFee + buyDevFee + buyBurnFee;
require(buyTotalFees <= 48, "Must keep fees at 48% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if(blockForPenaltyEnd > 0){
require(!boughtEarly[from] || to == owner() || to == address(0xdead), "Bots cannot transfer tokens in or out except to owner or dead address.");
}
if(limitsInEffect){
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if (transferDelayEnabled){
if (to != address(dexRouter) && to != address(lpPair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later.");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){
if(!boughtEarly[to]){
boughtEarly[to] = true;
botsCaught += 1;
emit CaughtEarlyBuyer(to);
}
fees = amount * 99 / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForOperations += fees * sellOperationsFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForOperations += fees * buyOperationsFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForBurn += fees * buyBurnFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function earlyBuyPenaltyInEffect() public view returns (bool){
return block.number < blockForPenaltyEnd;
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = dexRouter.WETH();
_approve(address(this), address(dexRouter), tokenAmount);
dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(dexRouter), tokenAmount);
address(this),
tokenAmount,
address(0xdead),
block.timestamp
);
}
dexRouter.addLiquidityETH{value: ethAmount}(
function swapBack() private {
if(tokensForBurn > 0 && balanceOf(address(this)) >= tokensForBurn) {
_burn(address(this), tokensForBurn);
}
tokensForBurn = 0;
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForOperations + tokensForDev;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
bool success;
swapTokensForEth(contractBalance - liquidityTokens);
uint256 ethBalance = address(this).balance;
uint256 ethForLiquidity = ethBalance;
uint256 ethForOperations = ethBalance * tokensForOperations / (totalTokensToSwap - (tokensForLiquidity/2));
uint256 ethForDev = ethBalance * tokensForDev / (totalTokensToSwap - (tokensForLiquidity/2));
ethForLiquidity -= ethForOperations + ethForDev;
tokensForLiquidity = 0;
tokensForOperations = 0;
tokensForDev = 0;
tokensForBurn = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
}
}
function swapBack() private {
if(tokensForBurn > 0 && balanceOf(address(this)) >= tokensForBurn) {
_burn(address(this), tokensForBurn);
}
tokensForBurn = 0;
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForOperations + tokensForDev;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
bool success;
swapTokensForEth(contractBalance - liquidityTokens);
uint256 ethBalance = address(this).balance;
uint256 ethForLiquidity = ethBalance;
uint256 ethForOperations = ethBalance * tokensForOperations / (totalTokensToSwap - (tokensForLiquidity/2));
uint256 ethForDev = ethBalance * tokensForDev / (totalTokensToSwap - (tokensForLiquidity/2));
ethForLiquidity -= ethForOperations + ethForDev;
tokensForLiquidity = 0;
tokensForOperations = 0;
tokensForDev = 0;
tokensForBurn = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
}
}
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
function swapBack() private {
if(tokensForBurn > 0 && balanceOf(address(this)) >= tokensForBurn) {
_burn(address(this), tokensForBurn);
}
tokensForBurn = 0;
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForOperations + tokensForDev;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
bool success;
swapTokensForEth(contractBalance - liquidityTokens);
uint256 ethBalance = address(this).balance;
uint256 ethForLiquidity = ethBalance;
uint256 ethForOperations = ethBalance * tokensForOperations / (totalTokensToSwap - (tokensForLiquidity/2));
uint256 ethForDev = ethBalance * tokensForDev / (totalTokensToSwap - (tokensForLiquidity/2));
ethForLiquidity -= ethForOperations + ethForDev;
tokensForLiquidity = 0;
tokensForOperations = 0;
tokensForDev = 0;
tokensForBurn = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
}
}
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
function swapBack() private {
if(tokensForBurn > 0 && balanceOf(address(this)) >= tokensForBurn) {
_burn(address(this), tokensForBurn);
}
tokensForBurn = 0;
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForOperations + tokensForDev;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
bool success;
swapTokensForEth(contractBalance - liquidityTokens);
uint256 ethBalance = address(this).balance;
uint256 ethForLiquidity = ethBalance;
uint256 ethForOperations = ethBalance * tokensForOperations / (totalTokensToSwap - (tokensForLiquidity/2));
uint256 ethForDev = ethBalance * tokensForDev / (totalTokensToSwap - (tokensForLiquidity/2));
ethForLiquidity -= ethForOperations + ethForDev;
tokensForLiquidity = 0;
tokensForOperations = 0;
tokensForDev = 0;
tokensForBurn = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
}
}
(success,) = address(devAddress).call{value: ethForDev}("");
(success,) = address(operationsAddress).call{value: address(this).balance}("");
function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) {
require(_token != address(0), "_token address cannot be 0");
require(_token != address(this), "Can't withdraw native tokens");
uint256 _contractBalance = IERC20(_token).balanceOf(address(this));
_sent = IERC20(_token).transfer(_to, _contractBalance);
emit TransferForeignToken(_token, _contractBalance);
}
function withdrawStuckETH() external onlyOwner {
bool success;
}
(success,) = address(msg.sender).call{value: address(this).balance}("");
function setOperationsAddress(address _operationsAddress) external onlyOwner {
require(_operationsAddress != address(0), "_operationsAddress address cannot be 0");
operationsAddress = payable(_operationsAddress);
}
function setDevAddress(address _devAddress) external onlyOwner {
require(_devAddress != address(0), "_devAddress address cannot be 0");
devAddress = payable(_devAddress);
}
function forceSwapBack() external onlyOwner {
require(balanceOf(address(this)) >= swapTokensAtAmount, "Can only swap when token amount is at or higher than restriction");
swapping = true;
swapBack();
swapping = false;
emit OwnerForcedSwapBack(block.timestamp);
}
function buyBackTokens(uint256 amountInWei) external onlyOwner {
require(amountInWei <= 10 ether, "May not buy more than 10 ETH in a single buy to reduce sandwich attacks");
address[] memory path = new address[](2);
path[0] = dexRouter.WETH();
path[1] = address(this);
path,
address(0xdead),
block.timestamp
);
emit BuyBackTriggered(amountInWei);
}
dexRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amountInWei}(
} | 4,445,614 | [
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
431,
17704,
1317,
628,
1656,
281,
471,
943,
2492,
3844,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
10426,
16057,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
203,
565,
2254,
5034,
1071,
943,
38,
9835,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
55,
1165,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
16936,
6275,
31,
203,
203,
565,
1599,
338,
8259,
1071,
302,
338,
8259,
31,
203,
565,
1758,
1071,
12423,
4154,
31,
203,
203,
565,
1426,
3238,
7720,
1382,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
203,
565,
1758,
5295,
1887,
31,
203,
565,
1758,
4461,
1887,
31,
203,
203,
565,
2254,
5034,
1071,
1203,
1290,
24251,
15006,
1638,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
1071,
800,
9540,
41,
20279,
31,
203,
565,
2254,
5034,
1071,
2512,
87,
24512,
31,
203,
203,
565,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
565,
1426,
1071,
1284,
7459,
3896,
273,
629,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
629,
31,
203,
203,
565,
1426,
1071,
7412,
6763,
1526,
273,
638,
31,
203,
203,
565,
2254,
5034,
1071,
30143,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
30143,
9343,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
48,
18988,
24237,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
8870,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
38,
321,
14667,
31,
203,
203,
565,
2254,
5034,
1071,
357,
80,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
357,
80,
9343,
14667,
31,
203,
565,
2254,
5034,
1071,
357,
80,
48,
18988,
24237,
14667,
31,
203,
565,
2254,
5034,
2
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-07
*/
// Litentry: Modified based on
// https://solidity-by-example.org/app/multi-sig-wallet/
// data:template
//
// (1) 0xcb10f215
/**
@notice Sets a new resource for handler contracts that use the IERCHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
// Function: adminSetResource(address handlerAddress, bytes32 resourceID, address tokenAddress)
// MethodID: 0xcb10f215
// [0]: 00000000000000000000000050272b13efbb3da7c25cf5b98339efbd19a2a855
// [1]: 0000000000000000000000000000000000000000000000000000000000000001
// [2]: 00000000000000000000000027b981dd46ae0bfdda6677ddc75bce6995fca5bc
//
//
//
// (2) 0x4e056005
/**
@notice Modifies the number of votes required for a proposal to be considered passed.
@notice Only callable by an address that currently has the admin role.
@param newThreshold Value {_relayerThreshold} will be changed to.
@notice Emits {RelayerThresholdChanged} event.
*/
// Function: adminChangeRelayerThreshold(uint256 newThreshold)
// MethodID: 0x4e056005
// [0]: 0000000000000000000000000000000000000000000000000000000000000001
//
//
//
// (3) 0xcdb0f73a
/**
@notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be added.
@notice Emits {RelayerAdded} event.
*/
// Function: adminAddRelayer(address relayerAddress)
// MethodID: 0xcdb0f73a
// [0]: 0000000000000000000000002aa87a1dd75df16a6b22dd1d94ae6c3d3be40e88
//
//
//
// (4) 0x9d82dd63
/**
@notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be removed.
@notice Emits {RelayerRemoved} event.
*/
// Function: adminRemoveRelayer(address relayerAddress)
// MethodID: 0x9d82dd63
// [0]: 0000000000000000000000002aa87a1dd75df16a6b22dd1d94ae6c3d3be40e88
//
//
//
// (5) 0x80ae1c28
/**
@notice Pauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
// Function adminPauseTransfers()
// MethodID: 0x80ae1c28
//
//
//
// (6) 0xffaac0eb
/**
@notice Unpauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
// Function adminUnpauseTransfers()
// MethodID: 0xffaac0eb
//
//
//
// (7) 0x5e1fab0f
/**
@notice Removes admin role from {msg.sender} and grants it to {newAdmin}.
@notice Only callable by an address that currently has the admin role.
@param newAdmin Address that admin role will be granted to.
*/
// Function renounceAdmin(address newAdmin)
// MethodID: 0x5e1fab0f
// [0]: 0000000000000000000000002aa87a1dd75df16a6b22dd1d94ae6c3d3be40e88
//
//
//
// (8) 0x17f03ce5
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data originally provided when deposit was made.
@notice Proposal must be past expiry threshold.
@notice Emits {ProposalEvent} event with status {Cancelled}.
*/
// Function cancelProposal(uint8 chainID, uint64 depositNonce, bytes32 dataHash)
// MethodID: 0x17f03ce5
// [0]: 0000000000000000000000000000000000000000000000000000000000000003
// [1]: 0000000000000000000000000000000000000000000000000000000000000007
// [2]: 00000000000000000000000000000063a7e2be78898ba83824b0c0cc8dfb6001
//
//
//
// (9) 0xc2d0c12d
/**
@notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1.
This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0.
@param addrs Array of addresses to transfer {amounts} to.
@param amounts Array of amonuts to transfer to {addrs}.
*/
// Function transferFunds(address payable[] calldata addrs, uint[] calldata amounts)
// MethodID: 0xc2d0c12d
// Too complicated. See official document for reference
// https://docs.soliditylang.org/en/develop/abi-spec.html#use-of-dynamic-types
//
//
//
// (10) 0x780cf004
/**
@notice Used to manually withdraw funds from ERC safes.
@param handlerAddress Address of handler to withdraw from.
@param tokenAddress Address of token to withdraw.
@param recipient Address to withdraw tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw.
*/
// Function adminWithdraw(address handlerAddress, address tokenAddress, address recipient, uint256 amountOrTokenID)
// MethodID: 0x780cf004
// [0]: 00000000000000000000000050272b13efbb3da7c25cf5b98339efbd19a2a855
// [1]: 00000000000000000000000027b981dd46ae0bfdda6677ddc75bce6995fca5bc
// [2]: 0000000000000000000000002aa87a1dd75df16a6b22dd1d94ae6c3d3be40e88
// [3]: 00000000000000000000000000000000000000000000000053444835ec580000
//
//
//
// (11) 0x7f3e3744
/**
@notice Changes deposit fee.
@notice Only callable by admin.
@param newFee Value {_fee} will be updated to.
*/
// Function adminChangeFee(uint newFee)
// MethodID: 0x7f3e3744
// [0]: 00000000000000000000000000000000000000000000000053444835ec580000
//
//
//
// (12) 0x8c0c2631
/**
@notice Sets a resource as burnable for handler contracts that use the IERCHandler interface.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
// Function adminSetBurnable(address handlerAddress, address tokenAddress)
// MethodID: 0x8c0c2631
// [0]: 00000000000000000000000050272b13efbb3da7c25cf5b98339efbd19a2a855
// [1]: 00000000000000000000000027b981dd46ae0bfdda6677ddc75bce6995fca5bc
//
//
//
// (13) 0xe8437ee7
/**
@notice Sets a new resource for handler contracts that use the IGenericHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
// Function adminSetGenericResource(address handlerAddress, bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig)
// MethodID: 0xe8437ee7
// [0]: 00000000000000000000000050272b13efbb3da7c25cf5b98339efbd19a2a855
// [1]: 00000000000000000000000000000063a7e2be78898ba83824b0c0cc8dfb6001
// [2]: 00000000000000000000000027b981dd46ae0bfdda6677ddc75bce6995fca5bc
// [3]: ****************************************************************
// [4]: ****************************************************************
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract MultiSigWallet {
event Deposit(address indexed sender, uint amount, uint balance);
event SubmitTransaction(
address indexed owner,
uint indexed txIndex,
address indexed to,
uint value,
bytes data
);
event ConfirmTransaction(address indexed owner, uint indexed txIndex);
event RevokeConfirmation(address indexed owner, uint indexed txIndex);
event ExecuteTransaction(address indexed owner, uint indexed txIndex);
event addProposer(address indexed proposer,address indexed owner);
event removeProposer(address indexed proposer, address indexed owner);
address[] public owners;
mapping(address => bool) public isOwner;
mapping(address => bool) public isProposer;
uint public numConfirmationsRequired;
struct Transaction {
address to;
uint value;
bytes data;
bool executed;
uint numConfirmations;
}
// mapping from tx index => owner => bool
mapping(uint => mapping(address => bool)) public isConfirmed;
Transaction[] public transactions;
modifier onlyOwner() {
require(isOwner[msg.sender], "not owner");
_;
}
modifier txExists(uint _txIndex) {
require(_txIndex < transactions.length, "tx does not exist");
_;
}
modifier notExecuted(uint _txIndex) {
require(!transactions[_txIndex].executed, "tx already executed");
_;
}
modifier notConfirmed(uint _txIndex) {
require(!isConfirmed[_txIndex][msg.sender], "tx already confirmed");
_;
}
constructor(address[] memory _owners, uint _numConfirmationsRequired) {
require(_owners.length > 0, "owners required");
require(
_numConfirmationsRequired > 0 &&
_numConfirmationsRequired <= _owners.length,
"invalid number of required confirmations"
);
for (uint i = 0; i < _owners.length; i++) {
address owner = _owners[i];
require(owner != address(0), "invalid owner");
require(!isOwner[owner], "owner not unique");
isOwner[owner] = true;
owners.push(owner);
}
numConfirmationsRequired = _numConfirmationsRequired;
}
receive() external payable {
emit Deposit(msg.sender, msg.value, address(this).balance);
}
function addProposers(address[] calldata _proposers) public onlyOwner {
for (uint i = 0; i < _proposers.length; i++) {
require(!isProposer[_proposers[i]], "proposer already");
isProposer[_proposers[i]] = true;
emit addProposer(_proposers[i], msg.sender);
}
}
function removeProposers(address[] calldata _proposers) public onlyOwner {
for (uint i = 0; i < _proposers.length; i++) {
require(isProposer[_proposers[i]], "not proposer already");
isProposer[_proposers[i]] = false;
emit removeProposer(_proposers[i], msg.sender);
}
}
function submitTransaction(
address _to,
uint _value,
bytes memory _data
) public {
require(isOwner[msg.sender] || isProposer[msg.sender], "not owner/proposer");
uint txIndex = transactions.length;
transactions.push(
Transaction({
to: _to,
value: _value,
data: _data,
executed: false,
numConfirmations: 0
})
);
emit SubmitTransaction(msg.sender, txIndex, _to, _value, _data);
}
function confirmTransaction(uint _txIndex)
public
onlyOwner
txExists(_txIndex)
notExecuted(_txIndex)
notConfirmed(_txIndex)
{
Transaction storage transaction = transactions[_txIndex];
transaction.numConfirmations += 1;
isConfirmed[_txIndex][msg.sender] = true;
emit ConfirmTransaction(msg.sender, _txIndex);
}
function executeTransaction(uint _txIndex)
public
onlyOwner
txExists(_txIndex)
notExecuted(_txIndex)
{
Transaction storage transaction = transactions[_txIndex];
require(
transaction.numConfirmations >= numConfirmationsRequired,
"cannot execute tx"
);
transaction.executed = true;
(bool success, ) = transaction.to.call{value: transaction.value}(
transaction.data
);
require(success, "tx failed");
emit ExecuteTransaction(msg.sender, _txIndex);
}
function revokeConfirmation(uint _txIndex)
public
onlyOwner
txExists(_txIndex)
notExecuted(_txIndex)
{
Transaction storage transaction = transactions[_txIndex];
require(isConfirmed[_txIndex][msg.sender], "tx not confirmed");
transaction.numConfirmations -= 1;
isConfirmed[_txIndex][msg.sender] = false;
emit RevokeConfirmation(msg.sender, _txIndex);
}
function getOwners() public view returns (address[] memory) {
return owners;
}
function getTransactionCount() public view returns (uint) {
return transactions.length;
}
function getTransaction(uint _txIndex)
public
view
returns (
address to,
uint value,
bytes memory data,
bool executed,
uint numConfirmations
)
{
Transaction storage transaction = transactions[_txIndex];
return (
transaction.to,
transaction.value,
transaction.data,
transaction.executed,
transaction.numConfirmations
);
}
} | / Function: adminAddRelayer(address relayerAddress) MethodID: 0xcdb0f73a [0]: 0000000000000000000000002aa87a1dd75df16a6b22dd1d94ae6c3d3be40e88 (4) 0x9d82dd63* | @notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count.
| 8,027,877 | [
1,
19,
4284,
30,
3981,
986,
1971,
1773,
12,
2867,
1279,
1773,
1887,
13,
2985,
734,
30,
374,
6511,
1966,
20,
74,
9036,
69,
306,
20,
14542,
225,
374,
12648,
12648,
9449,
3103,
7598,
11035,
69,
21,
449,
5877,
2180,
2313,
69,
26,
70,
3787,
449,
21,
72,
11290,
8906,
26,
71,
23,
72,
23,
2196,
7132,
73,
5482,
261,
24,
13,
374,
92,
29,
72,
11149,
449,
4449,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
632,
20392,
20284,
1279,
1773,
2478,
364,
288,
2878,
1773,
1887,
97,
471,
23850,
3304,
288,
67,
4963,
1971,
1773,
97,
1056,
18,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public 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);
event Burn(address indexed from, uint256 value);
}
// ----------------------------------------------------------------------------
// 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);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract ERC20Token is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function ERC20Token() public {
symbol = "DRON";
name = "Dron";
decimals = 8;
_totalSupply = 25000000 * 10 ** uint256(decimals); // 1 billion coins WE RICH
balances[msg.sender] = _totalSupply; // the address launching the token is msg sender
emit Transfer(address(0), msg.sender, _totalSupply); // trigger transfer event
}
// ------------------------------------------------------------------------
// 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);
emit 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;
emit 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) {
require(to != 0x0);
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit 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;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// 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);
}
//Destroy tokens
function burn(uint256 tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
require(balances[msg.sender] >= tokens); // Check if the sender has enough
balances[msg.sender] -= tokens; // Subtract from the sender
_totalSupply -= tokens; // Updates totalSupply
emit Burn(msg.sender, tokens);
return true;
}
// Destroy tokens from other account
function burnFrom(address from, uint256 tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
require(balances[from] >= tokens); // Check if the targeted balance is enough
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
require(tokens <= allowed[from][msg.sender]); // Check allowance
balances[from] -= tokens; // Subtract from the targeted balance
allowed[from][msg.sender] -= tokens; // Subtract from the sender's allowance
_totalSupply -= tokens; // Update totalSupply
emit Burn(from, 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) {
require(to != 0x0);
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
| 13,779,301 | [
1,
29461,
12279,
2430,
628,
326,
628,
2236,
358,
326,
358,
2236,
1021,
4440,
2236,
1297,
1818,
1240,
18662,
2430,
6617,
537,
5825,
24950,
72,
364,
272,
9561,
628,
326,
628,
2236,
471,
300,
6338,
2236,
1297,
1240,
18662,
11013,
358,
7412,
300,
348,
1302,
264,
1297,
1240,
18662,
1699,
1359,
358,
7412,
300,
374,
460,
29375,
854,
2935,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2254,
2430,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
2583,
12,
869,
480,
374,
92,
20,
1769,
203,
3639,
324,
26488,
63,
2080,
65,
273,
4183,
1676,
12,
70,
26488,
63,
2080,
6487,
2430,
1769,
203,
3639,
2935,
63,
2080,
6362,
3576,
18,
15330,
65,
273,
4183,
1676,
12,
8151,
63,
2080,
6362,
3576,
18,
15330,
6487,
2430,
1769,
203,
3639,
324,
26488,
63,
869,
65,
273,
4183,
986,
12,
70,
26488,
63,
869,
6487,
2430,
1769,
203,
3639,
3626,
12279,
12,
2080,
16,
358,
16,
2430,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-06
*/
// File: @openzeppelin/contracts/utils/Counters.sol
// OpenZeppelin Contracts v4.4.0 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.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 `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
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.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.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`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: contracts/FrenDAOGriffin.sol
//Contract based on https://docs.openzeppelin.com/contracts/3.x/erc721
pragma solidity ^0.8.0;
contract FrenDAOGriffin is ERC721, Ownable {
using Counters for Counters.Counter;
uint256 public constant MAX_GRIFFIN_PURCHASE = 3;
uint256 public constant MAX_SUPPLY = 10;
string public constant GRIFFIN_URI = "https://gateway.pinata.cloud/ipfs/QmPk4AwMjrmKJtmXvQbmzDdiCg1JL4ECe6gbHziWHMNwUf";
uint256 public griffinPrice = 0.11 ether;
address treasury = 0xd26c75c33F8818900Fa9136D8387382a5bc1B5E9;
uint256 public saleStartTime = type(uint256).max;
Counters.Counter private _tokenIds;
mapping(address => uint256) public mintedPerAccount;
constructor(uint256 startTime) Ownable() ERC721("FrenDAO Griffin", "FRENG") {
saleStartTime = startTime;
}
function withdraw() external onlyOwner {
require(payable(treasury).send(address(this).balance));
}
function setOhmGriffinPrice(uint256 newGriffinPrice) external onlyOwner {
griffinPrice = newGriffinPrice;
}
function setSaleStartTime(uint256 startTime) external onlyOwner {
saleStartTime = startTime;
}
function mintNFT(uint256 numberOfTokens) external payable {
require(block.timestamp >= saleStartTime, "Sale must be active to mint an Griffin");
require(block.timestamp <= saleStartTime + 7 days, "Sale has ended");
require(numberOfTokens > 0, "Cant mint 0");
require(mintedPerAccount[msg.sender]+numberOfTokens <= MAX_GRIFFIN_PURCHASE, "Past account limit");
require(msg.value == griffinPrice * numberOfTokens, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
_mintNFT(msg.sender);
}
}
function totalSupply() external view returns (uint256) {
return _tokenIds.current();
}
function _mintNFT(address to) internal {
require(_tokenIds.current() < MAX_SUPPLY, "MAX_SUPPLY");
mintedPerAccount[to]++;
uint256 newItemId = _tokenIds.current();
_tokenIds.increment();
_mint(to, newItemId);
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _baseURI();
}
function _baseURI() internal view virtual override returns (string memory) {
return GRIFFIN_URI;
}
} | File: contracts/FrenDAOGriffin.solContract based on https:docs.openzeppelin.com/contracts/3.x/erc721 | contract FrenDAOGriffin is ERC721, Ownable {
using Counters for Counters.Counter;
uint256 public constant MAX_GRIFFIN_PURCHASE = 3;
uint256 public constant MAX_SUPPLY = 10;
uint256 public griffinPrice = 0.11 ether;
address treasury = 0xd26c75c33F8818900Fa9136D8387382a5bc1B5E9;
uint256 public saleStartTime = type(uint256).max;
Counters.Counter private _tokenIds;
mapping(address => uint256) public mintedPerAccount;
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
pragma solidity ^0.8.0;
constructor(uint256 startTime) Ownable() ERC721("FrenDAO Griffin", "FRENG") {
saleStartTime = startTime;
}
function withdraw() external onlyOwner {
require(payable(treasury).send(address(this).balance));
}
function setOhmGriffinPrice(uint256 newGriffinPrice) external onlyOwner {
griffinPrice = newGriffinPrice;
}
function setSaleStartTime(uint256 startTime) external onlyOwner {
saleStartTime = startTime;
}
function mintNFT(uint256 numberOfTokens) external payable {
require(block.timestamp >= saleStartTime, "Sale must be active to mint an Griffin");
require(block.timestamp <= saleStartTime + 7 days, "Sale has ended");
require(numberOfTokens > 0, "Cant mint 0");
require(mintedPerAccount[msg.sender]+numberOfTokens <= MAX_GRIFFIN_PURCHASE, "Past account limit");
require(msg.value == griffinPrice * numberOfTokens, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
_mintNFT(msg.sender);
}
}
function mintNFT(uint256 numberOfTokens) external payable {
require(block.timestamp >= saleStartTime, "Sale must be active to mint an Griffin");
require(block.timestamp <= saleStartTime + 7 days, "Sale has ended");
require(numberOfTokens > 0, "Cant mint 0");
require(mintedPerAccount[msg.sender]+numberOfTokens <= MAX_GRIFFIN_PURCHASE, "Past account limit");
require(msg.value == griffinPrice * numberOfTokens, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
_mintNFT(msg.sender);
}
}
function totalSupply() external view returns (uint256) {
return _tokenIds.current();
}
function _mintNFT(address to) internal {
require(_tokenIds.current() < MAX_SUPPLY, "MAX_SUPPLY");
mintedPerAccount[to]++;
uint256 newItemId = _tokenIds.current();
_tokenIds.increment();
_mint(to, newItemId);
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _baseURI();
}
function _baseURI() internal view virtual override returns (string memory) {
return GRIFFIN_URI;
}
} | 7,987,820 | [
1,
812,
30,
20092,
19,
42,
1187,
9793,
13369,
86,
430,
926,
18,
18281,
8924,
2511,
603,
2333,
30,
8532,
18,
3190,
94,
881,
84,
292,
267,
18,
832,
19,
16351,
87,
19,
23,
18,
92,
19,
12610,
27,
5340,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
478,
1187,
9793,
13369,
86,
430,
926,
353,
4232,
39,
27,
5340,
16,
14223,
6914,
288,
377,
203,
565,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
7010,
203,
565,
2254,
5034,
1071,
5381,
4552,
67,
43,
2259,
2246,
706,
67,
52,
1099,
1792,
4429,
273,
890,
31,
203,
565,
2254,
5034,
1071,
5381,
4552,
67,
13272,
23893,
273,
1728,
31,
203,
203,
565,
2254,
5034,
1071,
3821,
430,
926,
5147,
273,
374,
18,
2499,
225,
2437,
31,
203,
203,
565,
1758,
9787,
345,
22498,
273,
374,
7669,
5558,
71,
5877,
71,
3707,
42,
5482,
29426,
713,
29634,
29,
26959,
40,
28,
7414,
27,
7414,
22,
69,
25,
13459,
21,
38,
25,
41,
29,
31,
203,
203,
565,
2254,
5034,
1071,
272,
5349,
13649,
273,
618,
12,
11890,
5034,
2934,
1896,
31,
203,
203,
565,
9354,
87,
18,
4789,
3238,
389,
2316,
2673,
31,
377,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
312,
474,
329,
2173,
3032,
31,
203,
203,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
97,
203,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
203,
203,
203,
565,
3885,
12,
11890,
5034,
8657,
13,
14223,
6914,
1435,
4232,
39,
27,
5340,
2932,
42,
1187,
18485,
611,
86,
430,
926,
3113,
315,
42,
862,
4960,
7923,
288,
203,
3639,
272,
5349,
13649,
273,
8657,
31,
7010,
565,
289,
203,
203,
565,
2
] |
./full_match/137/0x1D5cF9684e87149867e9c36Bac1176c8BF2f7752/sources/contracts/ERC20Deflationary.sol | / Keeps track of balances for address that are included in receiving reward. Keeps track of balances for address that are excluded from receiving reward. Keeps track of which address are excluded from fee. Keeps track of which address are excluded from reward. An array of addresses that are excluded from reward. ERC20 Token Standard Liquidity pool provider router This Token and WETH pair contract address. Where burnt tokens are sent to. This is an address that no one can have accesses to. Decimals of taxBurn. Used for have tax less than 1%. Decimals of taxReward. Used for have tax less than 1%. Decimals of taxLiquify. Used for have tax less than 1%. This percent of a transaction will be burnt. This percent of a transaction will be redistribute to all holders. This percent of a transaction will be added to the liquidity pool. More details at https:github.com/Sheldenshi/ERC20Deflationary. ERC20 Token Standard ERC20 Token Standard Current supply:= total supply - burnt tokens A number that helps distributing fees to all holders respectively. Total amount of tokens rewarded / distributing. Total amount of tokens burnt. Total amount of tokens locked in the LP (this token and WETH pair). Total amount of ETH locked in the LP (this token and WETH pair). A threshold for swap and liquify. ERC20 Token Standard ERC20 Token Standard Whether a previous call of SwapAndLiquify process is still in process. Prevent reentrancy. | contract ERC20Deflationary is Context, IERC20, Ownable {
mapping (address => uint256) private _reflectionBalances;
mapping (address => uint256) private _tokenBalances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcludedFromReward;
address[] private _excludedFromReward;
mapping (address => mapping (address => uint256)) private _allowances;
IUniswapV2Router02 internal _uniswapV2Router;
address internal _uniswapV2Pair;
address private constant burnAccount = 0x000000000000000000000000000000000000dEaD;
Tax rate = (_taxXXX / 10**_tax_XXXDecimals) percent.
For example: if _taxBurn is 1 and _taxBurnDecimals is 2.
Tax rate = 0.01%
If you want tax rate for burn to be 5% for example,
set _taxBurn to 5 and _taxBurnDecimals to 0.
5 * (10 ** 0) = 5
uint8 private _taxBurnDecimals;
uint8 private _taxRewardDecimals;
uint8 private _taxLiquifyDecimals;
uint8 private _taxBurn;
uint8 private _taxReward;
uint8 private _taxLiquify;
uint8 private _decimals;
uint256 private _totalSupply;
uint256 private _currentSupply;
uint256 private _reflectionTotal;
uint256 private _totalRewarded;
uint256 private _totalBurnt;
uint256 private _totalTokensLockedInLiquidity;
uint256 private _totalETHLockedInLiquidity;
uint256 private _minTokensBeforeSwap;
string private _name;
string private _symbol;
bool private _inSwapAndLiquify;
bool private _autoSwapAndLiquifyEnabled;
bool private _autoBurnEnabled;
bool private _rewardEnabled;
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
modifier lockTheSwap {
require(!_inSwapAndLiquify, "Currently in swap and liquify.");
_inSwapAndLiquify = true;
_;
_inSwapAndLiquify = false;
}
struct ValuesFromAmount {
uint256 amount;
uint256 tBurnFee;
uint256 tRewardFee;
uint256 tLiquifyFee;
uint256 tTransferAmount;
uint256 rAmount;
uint256 rBurnFee;
uint256 rRewardFee;
uint256 rLiquifyFee;
uint256 rTransferAmount;
}
event TaxBurnUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal);
event TaxRewardUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal);
event TaxLiquifyUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal);
event MinTokensBeforeSwapUpdated(uint256 previous, uint256 current);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensAddedToLiquidity
);
event ExcludeAccountFromReward(address account);
event IncludeAccountInReward(address account);
event ExcludeAccountFromFee(address account);
event IncludeAccountInFee(address account);
event EnabledAutoBurn();
event EnabledReward();
event EnabledAutoSwapAndLiquify();
event DisabledAutoBurn();
event DisabledReward();
event DisabledAutoSwapAndLiquify();
event Airdrop(uint256 amount);
Events
event Burn(address from, uint256 amount);
constructor (string memory name_, string memory symbol_, uint8 decimals_, uint256 tokenSupply_) {
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
_totalSupply = tokenSupply_ * (10 ** decimals_);
_currentSupply = _totalSupply;
_reflectionTotal = (~uint256(0) - (~uint256(0) % _totalSupply));
_reflectionBalances[_msgSender()] = _reflectionTotal;
excludeAccountFromFee(owner());
excludeAccountFromFee(address(this));
_excludeAccountFromReward(owner());
_excludeAccountFromReward(burnAccount);
_excludeAccountFromReward(address(this));
emit Transfer(address(0), _msgSender(), _totalSupply);
}
receive() external payable {}
function name() public view virtual returns (string memory) {
return _name;
}
function symbol() public view virtual returns (string memory) {
return _symbol;
}
function decimals() public view virtual returns (uint8) {
return _decimals;
}
function uniswapV2Pair() public view virtual returns (address) {
return _uniswapV2Pair;
}
function taxBurn() public view virtual returns (uint8) {
return _taxBurn;
}
function taxReward() public view virtual returns (uint8) {
return _taxReward;
}
function taxLiquify() public view virtual returns (uint8) {
return _taxLiquify;
}
function taxBurnDecimals() public view virtual returns (uint8) {
return _taxBurnDecimals;
}
function taxRewardDecimals() public view virtual returns (uint8) {
return _taxRewardDecimals;
}
function taxLiquifyDecimals() public view virtual returns (uint8) {
return _taxLiquifyDecimals;
}
function autoBurnEnabled() public view virtual returns (bool) {
return _autoBurnEnabled;
}
function rewardEnabled() public view virtual returns (bool) {
return _rewardEnabled;
}
function autoSwapAndLiquifyEnabled() public view virtual returns (bool) {
return _autoSwapAndLiquifyEnabled;
}
function minTokensBeforeSwap() external view virtual returns (uint256) {
return _minTokensBeforeSwap;
}
function totalSupply() external view virtual override returns (uint256) {
return _totalSupply;
}
function currentSupply() external view virtual returns (uint256) {
return _currentSupply;
}
function totalBurnt() external view virtual returns (uint256) {
return _totalBurnt;
}
function totalTokensLockedInLiquidity() external view virtual returns (uint256) {
return _totalTokensLockedInLiquidity;
}
function totalETHLockedInLiquidity() external view virtual returns (uint256) {
return _totalETHLockedInLiquidity;
}
function balanceOf(address account) public view virtual override returns (uint256) {
if (_isExcludedFromReward[account]) return _tokenBalances[account];
return tokenFromReflection(_reflectionBalances[account]);
}
function isExcludedFromReward(address account) external view returns (bool) {
return _isExcludedFromReward[account];
}
function isExcludedFromFee(address account) external view returns (bool) {
return _isExcludedFromFee[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
require(_allowances[sender][_msgSender()] >= amount, "ERC20: transfer amount exceeds allowance");
_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) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function _burn(address account, uint256 amount) internal virtual {
require(account != burnAccount, "ERC20: burn from the burn address");
uint256 accountBalance = balanceOf(account);
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
uint256 rAmount = _getRAmount(amount);
if (_isExcludedFromReward[account]) {
_tokenBalances[account] -= amount;
}
_reflectionBalances[account] -= rAmount;
_tokenBalances[burnAccount] += amount;
_reflectionBalances[burnAccount] += rAmount;
_currentSupply -= amount;
_totalBurnt += amount;
emit Burn(account, amount);
emit Transfer(account, burnAccount, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != burnAccount, "ERC20: burn from the burn address");
uint256 accountBalance = balanceOf(account);
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
uint256 rAmount = _getRAmount(amount);
if (_isExcludedFromReward[account]) {
_tokenBalances[account] -= amount;
}
_reflectionBalances[account] -= rAmount;
_tokenBalances[burnAccount] += amount;
_reflectionBalances[burnAccount] += rAmount;
_currentSupply -= amount;
_totalBurnt += amount;
emit Burn(account, amount);
emit Transfer(account, burnAccount, amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _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");
ValuesFromAmount memory values = _getValues(amount, _isExcludedFromFee[sender]);
if (_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) {
_transferFromExcluded(sender, recipient, values);
_transferToExcluded(sender, recipient, values);
_transferStandard(sender, recipient, values);
_transferBothExcluded(sender, recipient, values);
_transferStandard(sender, recipient, values);
}
emit Transfer(sender, recipient, values.tTransferAmount);
if (!_isExcludedFromFee[sender]) {
_afterTokenTransfer(values);
}
}
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");
ValuesFromAmount memory values = _getValues(amount, _isExcludedFromFee[sender]);
if (_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) {
_transferFromExcluded(sender, recipient, values);
_transferToExcluded(sender, recipient, values);
_transferStandard(sender, recipient, values);
_transferBothExcluded(sender, recipient, values);
_transferStandard(sender, recipient, values);
}
emit Transfer(sender, recipient, values.tTransferAmount);
if (!_isExcludedFromFee[sender]) {
_afterTokenTransfer(values);
}
}
} else if (!_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) {
} else if (!_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) {
} else if (_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) {
} else {
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");
ValuesFromAmount memory values = _getValues(amount, _isExcludedFromFee[sender]);
if (_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) {
_transferFromExcluded(sender, recipient, values);
_transferToExcluded(sender, recipient, values);
_transferStandard(sender, recipient, values);
_transferBothExcluded(sender, recipient, values);
_transferStandard(sender, recipient, values);
}
emit Transfer(sender, recipient, values.tTransferAmount);
if (!_isExcludedFromFee[sender]) {
_afterTokenTransfer(values);
}
}
function _afterTokenTransfer(ValuesFromAmount memory values) internal virtual {
if (_autoBurnEnabled) {
_tokenBalances[address(this)] += values.tBurnFee;
_reflectionBalances[address(this)] += values.rBurnFee;
_approve(address(this), _msgSender(), values.tBurnFee);
burnFrom(address(this), values.tBurnFee);
}
if (_rewardEnabled) {
_distributeFee(values.rRewardFee, values.tRewardFee);
}
if (_autoSwapAndLiquifyEnabled) {
_tokenBalances[address(this)] += values.tLiquifyFee;
_reflectionBalances[address(this)] += values.rLiquifyFee;
uint256 contractBalance = _tokenBalances[address(this)];
bool overMinTokensBeforeSwap = contractBalance >= _minTokensBeforeSwap;
if (overMinTokensBeforeSwap &&
!_inSwapAndLiquify &&
_msgSender() != _uniswapV2Pair &&
_autoSwapAndLiquifyEnabled
)
{
swapAndLiquify(contractBalance);
}
}
}
function _afterTokenTransfer(ValuesFromAmount memory values) internal virtual {
if (_autoBurnEnabled) {
_tokenBalances[address(this)] += values.tBurnFee;
_reflectionBalances[address(this)] += values.rBurnFee;
_approve(address(this), _msgSender(), values.tBurnFee);
burnFrom(address(this), values.tBurnFee);
}
if (_rewardEnabled) {
_distributeFee(values.rRewardFee, values.tRewardFee);
}
if (_autoSwapAndLiquifyEnabled) {
_tokenBalances[address(this)] += values.tLiquifyFee;
_reflectionBalances[address(this)] += values.rLiquifyFee;
uint256 contractBalance = _tokenBalances[address(this)];
bool overMinTokensBeforeSwap = contractBalance >= _minTokensBeforeSwap;
if (overMinTokensBeforeSwap &&
!_inSwapAndLiquify &&
_msgSender() != _uniswapV2Pair &&
_autoSwapAndLiquifyEnabled
)
{
swapAndLiquify(contractBalance);
}
}
}
function _afterTokenTransfer(ValuesFromAmount memory values) internal virtual {
if (_autoBurnEnabled) {
_tokenBalances[address(this)] += values.tBurnFee;
_reflectionBalances[address(this)] += values.rBurnFee;
_approve(address(this), _msgSender(), values.tBurnFee);
burnFrom(address(this), values.tBurnFee);
}
if (_rewardEnabled) {
_distributeFee(values.rRewardFee, values.tRewardFee);
}
if (_autoSwapAndLiquifyEnabled) {
_tokenBalances[address(this)] += values.tLiquifyFee;
_reflectionBalances[address(this)] += values.rLiquifyFee;
uint256 contractBalance = _tokenBalances[address(this)];
bool overMinTokensBeforeSwap = contractBalance >= _minTokensBeforeSwap;
if (overMinTokensBeforeSwap &&
!_inSwapAndLiquify &&
_msgSender() != _uniswapV2Pair &&
_autoSwapAndLiquifyEnabled
)
{
swapAndLiquify(contractBalance);
}
}
}
function _afterTokenTransfer(ValuesFromAmount memory values) internal virtual {
if (_autoBurnEnabled) {
_tokenBalances[address(this)] += values.tBurnFee;
_reflectionBalances[address(this)] += values.rBurnFee;
_approve(address(this), _msgSender(), values.tBurnFee);
burnFrom(address(this), values.tBurnFee);
}
if (_rewardEnabled) {
_distributeFee(values.rRewardFee, values.tRewardFee);
}
if (_autoSwapAndLiquifyEnabled) {
_tokenBalances[address(this)] += values.tLiquifyFee;
_reflectionBalances[address(this)] += values.rLiquifyFee;
uint256 contractBalance = _tokenBalances[address(this)];
bool overMinTokensBeforeSwap = contractBalance >= _minTokensBeforeSwap;
if (overMinTokensBeforeSwap &&
!_inSwapAndLiquify &&
_msgSender() != _uniswapV2Pair &&
_autoSwapAndLiquifyEnabled
)
{
swapAndLiquify(contractBalance);
}
}
}
function _afterTokenTransfer(ValuesFromAmount memory values) internal virtual {
if (_autoBurnEnabled) {
_tokenBalances[address(this)] += values.tBurnFee;
_reflectionBalances[address(this)] += values.rBurnFee;
_approve(address(this), _msgSender(), values.tBurnFee);
burnFrom(address(this), values.tBurnFee);
}
if (_rewardEnabled) {
_distributeFee(values.rRewardFee, values.tRewardFee);
}
if (_autoSwapAndLiquifyEnabled) {
_tokenBalances[address(this)] += values.tLiquifyFee;
_reflectionBalances[address(this)] += values.rLiquifyFee;
uint256 contractBalance = _tokenBalances[address(this)];
bool overMinTokensBeforeSwap = contractBalance >= _minTokensBeforeSwap;
if (overMinTokensBeforeSwap &&
!_inSwapAndLiquify &&
_msgSender() != _uniswapV2Pair &&
_autoSwapAndLiquifyEnabled
)
{
swapAndLiquify(contractBalance);
}
}
}
function _transferStandard(address sender, address recipient, ValuesFromAmount memory values) private {
_reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount;
_reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount;
}
function _transferToExcluded(address sender, address recipient, ValuesFromAmount memory values) private {
_reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount;
_tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount;
_reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount;
}
function _transferFromExcluded(address sender, address recipient, ValuesFromAmount memory values) private {
_tokenBalances[sender] = _tokenBalances[sender] - values.amount;
_reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount;
_reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount;
}
function _transferBothExcluded(address sender, address recipient, ValuesFromAmount memory values) private {
_tokenBalances[sender] = _tokenBalances[sender] - values.amount;
_reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount;
_tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount;
_reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount;
}
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
function _excludeAccountFromReward(address account) internal {
require(!_isExcludedFromReward[account], "Account is already excluded.");
if(_reflectionBalances[account] > 0) {
_tokenBalances[account] = tokenFromReflection(_reflectionBalances[account]);
}
_isExcludedFromReward[account] = true;
_excludedFromReward.push(account);
emit ExcludeAccountFromReward(account);
}
function _excludeAccountFromReward(address account) internal {
require(!_isExcludedFromReward[account], "Account is already excluded.");
if(_reflectionBalances[account] > 0) {
_tokenBalances[account] = tokenFromReflection(_reflectionBalances[account]);
}
_isExcludedFromReward[account] = true;
_excludedFromReward.push(account);
emit ExcludeAccountFromReward(account);
}
function _includeAccountInReward(address account) internal {
require(_isExcludedFromReward[account], "Account is already included.");
for (uint256 i = 0; i < _excludedFromReward.length; i++) {
if (_excludedFromReward[i] == account) {
_excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1];
_tokenBalances[account] = 0;
_isExcludedFromReward[account] = false;
_excludedFromReward.pop();
break;
}
}
emit IncludeAccountInReward(account);
}
function _includeAccountInReward(address account) internal {
require(_isExcludedFromReward[account], "Account is already included.");
for (uint256 i = 0; i < _excludedFromReward.length; i++) {
if (_excludedFromReward[i] == account) {
_excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1];
_tokenBalances[account] = 0;
_isExcludedFromReward[account] = false;
_excludedFromReward.pop();
break;
}
}
emit IncludeAccountInReward(account);
}
function _includeAccountInReward(address account) internal {
require(_isExcludedFromReward[account], "Account is already included.");
for (uint256 i = 0; i < _excludedFromReward.length; i++) {
if (_excludedFromReward[i] == account) {
_excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1];
_tokenBalances[account] = 0;
_isExcludedFromReward[account] = false;
_excludedFromReward.pop();
break;
}
}
emit IncludeAccountInReward(account);
}
function excludeAccountFromFee(address account) internal {
require(!_isExcludedFromFee[account], "Account is already excluded.");
_isExcludedFromFee[account] = true;
emit ExcludeAccountFromFee(account);
}
function includeAccountInFee(address account) internal {
require(_isExcludedFromFee[account], "Account is already included.");
_isExcludedFromFee[account] = false;
emit IncludeAccountInFee(account);
}
function airdrop(uint256 amount) public {
address sender = _msgSender();
require(balanceOf(sender) >= amount, "The caller must have balance >= amount.");
ValuesFromAmount memory values = _getValues(amount, false);
if (_isExcludedFromReward[sender]) {
_tokenBalances[sender] -= values.amount;
}
_reflectionBalances[sender] -= values.rAmount;
_reflectionTotal = _reflectionTotal - values.rAmount;
_totalRewarded += amount ;
emit Airdrop(amount);
}
function airdrop(uint256 amount) public {
address sender = _msgSender();
require(balanceOf(sender) >= amount, "The caller must have balance >= amount.");
ValuesFromAmount memory values = _getValues(amount, false);
if (_isExcludedFromReward[sender]) {
_tokenBalances[sender] -= values.amount;
}
_reflectionBalances[sender] -= values.rAmount;
_reflectionTotal = _reflectionTotal - values.rAmount;
_totalRewarded += amount ;
emit Airdrop(amount);
}
function reflectionFromToken(uint256 amount, bool deductTransferFee) internal view returns(uint256) {
require(amount <= _totalSupply, "Amount must be less than supply");
ValuesFromAmount memory values = _getValues(amount, deductTransferFee);
return values.rTransferAmount;
}
function tokenFromReflection(uint256 rAmount) internal view returns(uint256) {
require(rAmount <= _reflectionTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount / currentRate;
}
function swapAndLiquify(uint256 contractBalance) private lockTheSwap {
uint256 tokensToSwap = contractBalance / 2;
uint256 tokensAddToLiquidity = contractBalance - tokensToSwap;
uint256 initialBalance = address(this).balance;
swapTokensForEth(tokensToSwap);
uint256 ethAddToLiquify = address(this).balance - initialBalance;
addLiquidity(ethAddToLiquify, tokensAddToLiquidity);
_totalETHLockedInLiquidity += address(this).balance - initialBalance;
_totalTokensLockedInLiquidity += contractBalance - balanceOf(address(this));
emit SwapAndLiquify(tokensToSwap, ethAddToLiquify, tokensAddToLiquidity);
}
function swapTokensForEth(uint256 amount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = _uniswapV2Router.WETH();
_approve(address(this), address(_uniswapV2Router), amount);
_uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amount,
0,
path,
block.timestamp + 60 * 1000
);
}
function addLiquidity(uint256 ethAmount, uint256 tokenAmount) private {
_approve(address(this), address(_uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
block.timestamp + 60 * 1000
);
}
_uniswapV2Router.addLiquidityETH{value: ethAmount}(
function _distributeFee(uint256 rRewardFee, uint256 tRewardFee) private {
_reflectionTotal = _reflectionTotal - rRewardFee;
_totalRewarded += tRewardFee;
}
function _getValues(uint256 amount, bool deductTransferFee) private view returns (ValuesFromAmount memory) {
ValuesFromAmount memory values;
values.amount = amount;
_getTValues(values, deductTransferFee);
_getRValues(values, deductTransferFee);
return values;
}
function _getTValues(ValuesFromAmount memory values, bool deductTransferFee) view private {
if (deductTransferFee) {
values.tTransferAmount = values.amount;
values.tBurnFee = _calculateTax(values.amount, _taxBurn, _taxBurnDecimals);
values.tRewardFee = _calculateTax(values.amount, _taxReward, _taxRewardDecimals);
values.tLiquifyFee = _calculateTax(values.amount, _taxLiquify, _taxLiquifyDecimals);
values.tTransferAmount = values.amount - values.tBurnFee - values.tRewardFee - values.tLiquifyFee;
}
}
function _getTValues(ValuesFromAmount memory values, bool deductTransferFee) view private {
if (deductTransferFee) {
values.tTransferAmount = values.amount;
values.tBurnFee = _calculateTax(values.amount, _taxBurn, _taxBurnDecimals);
values.tRewardFee = _calculateTax(values.amount, _taxReward, _taxRewardDecimals);
values.tLiquifyFee = _calculateTax(values.amount, _taxLiquify, _taxLiquifyDecimals);
values.tTransferAmount = values.amount - values.tBurnFee - values.tRewardFee - values.tLiquifyFee;
}
}
} else {
function _getRValues(ValuesFromAmount memory values, bool deductTransferFee) view private {
uint256 currentRate = _getRate();
values.rAmount = values.amount * currentRate;
if (deductTransferFee) {
values.rTransferAmount = values.rAmount;
values.rAmount = values.amount * currentRate;
values.rBurnFee = values.tBurnFee * currentRate;
values.rRewardFee = values.tRewardFee * currentRate;
values.rLiquifyFee = values.tLiquifyFee * currentRate;
values.rTransferAmount = values.rAmount - values.rBurnFee - values.rRewardFee - values.rLiquifyFee;
}
}
function _getRValues(ValuesFromAmount memory values, bool deductTransferFee) view private {
uint256 currentRate = _getRate();
values.rAmount = values.amount * currentRate;
if (deductTransferFee) {
values.rTransferAmount = values.rAmount;
values.rAmount = values.amount * currentRate;
values.rBurnFee = values.tBurnFee * currentRate;
values.rRewardFee = values.tRewardFee * currentRate;
values.rLiquifyFee = values.tLiquifyFee * currentRate;
values.rTransferAmount = values.rAmount - values.rBurnFee - values.rRewardFee - values.rLiquifyFee;
}
}
} else {
function _getRAmount(uint256 amount) private view returns (uint256) {
uint256 currentRate = _getRate();
return amount * currentRate;
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply / tSupply;
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _reflectionTotal;
uint256 tSupply = _totalSupply;
for (uint256 i = 0; i < _excludedFromReward.length; i++) {
if (_reflectionBalances[_excludedFromReward[i]] > rSupply || _tokenBalances[_excludedFromReward[i]] > tSupply) return (_reflectionTotal, _totalSupply);
rSupply = rSupply - _reflectionBalances[_excludedFromReward[i]];
tSupply = tSupply - _tokenBalances[_excludedFromReward[i]];
}
if (rSupply < _reflectionTotal / _totalSupply) return (_reflectionTotal, _totalSupply);
return (rSupply, tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _reflectionTotal;
uint256 tSupply = _totalSupply;
for (uint256 i = 0; i < _excludedFromReward.length; i++) {
if (_reflectionBalances[_excludedFromReward[i]] > rSupply || _tokenBalances[_excludedFromReward[i]] > tSupply) return (_reflectionTotal, _totalSupply);
rSupply = rSupply - _reflectionBalances[_excludedFromReward[i]];
tSupply = tSupply - _tokenBalances[_excludedFromReward[i]];
}
if (rSupply < _reflectionTotal / _totalSupply) return (_reflectionTotal, _totalSupply);
return (rSupply, tSupply);
}
function _calculateTax(uint256 amount, uint8 tax, uint8 taxDecimals_) private pure returns (uint256) {
return amount * tax / (10 ** taxDecimals_) / (10 ** 2);
}
Owner functions
function enableAutoBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner {
require(!_autoBurnEnabled, "Auto burn feature is already enabled.");
require(taxBurn_ > 0, "Tax must be greater than 0.");
require(taxBurnDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2");
_autoBurnEnabled = true;
setTaxBurn(taxBurn_, taxBurnDecimals_);
emit EnabledAutoBurn();
}
function enableReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner {
require(!_rewardEnabled, "Reward feature is already enabled.");
require(taxReward_ > 0, "Tax must be greater than 0.");
require(taxRewardDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2");
_rewardEnabled = true;
setTaxReward(taxReward_, taxRewardDecimals_);
emit EnabledReward();
}
function enableAutoSwapAndLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_, address routerAddress, uint256 minTokensBeforeSwap_) public onlyOwner {
require(!_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature is already enabled.");
require(taxLiquify_ > 0, "Tax must be greater than 0.");
require(taxLiquifyDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2");
_minTokensBeforeSwap = minTokensBeforeSwap_;
IUniswapV2Router02 uniswapV2Router = IUniswapV2Router02(routerAddress);
_uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).getPair(address(this), uniswapV2Router.WETH());
if (_uniswapV2Pair == address(0)) {
_uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
}
_uniswapV2Router = uniswapV2Router;
setTaxLiquify(taxLiquify_, taxLiquifyDecimals_);
emit EnabledAutoSwapAndLiquify();
}
function enableAutoSwapAndLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_, address routerAddress, uint256 minTokensBeforeSwap_) public onlyOwner {
require(!_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature is already enabled.");
require(taxLiquify_ > 0, "Tax must be greater than 0.");
require(taxLiquifyDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2");
_minTokensBeforeSwap = minTokensBeforeSwap_;
IUniswapV2Router02 uniswapV2Router = IUniswapV2Router02(routerAddress);
_uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).getPair(address(this), uniswapV2Router.WETH());
if (_uniswapV2Pair == address(0)) {
_uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
}
_uniswapV2Router = uniswapV2Router;
setTaxLiquify(taxLiquify_, taxLiquifyDecimals_);
emit EnabledAutoSwapAndLiquify();
}
_excludeAccountFromReward(address(uniswapV2Router));
_excludeAccountFromReward(_uniswapV2Pair);
excludeAccountFromFee(address(uniswapV2Router));
excludeAccountFromFee(_uniswapV2Pair);
_autoSwapAndLiquifyEnabled = true;
function disableAutoBurn() public onlyOwner {
require(_autoBurnEnabled, "Auto burn feature is already disabled.");
setTaxBurn(0, 0);
_autoBurnEnabled = false;
emit DisabledAutoBurn();
}
function disableReward() public onlyOwner {
require(_rewardEnabled, "Reward feature is already disabled.");
setTaxReward(0, 0);
_rewardEnabled = false;
emit DisabledReward();
}
function disableAutoSwapAndLiquify() public onlyOwner {
require(_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature is already disabled.");
setTaxLiquify(0, 0);
_autoSwapAndLiquifyEnabled = false;
emit DisabledAutoSwapAndLiquify();
}
function setMinTokensBeforeSwap(uint256 minTokensBeforeSwap_) public onlyOwner {
require(minTokensBeforeSwap_ < _currentSupply, "minTokensBeforeSwap must be higher than current supply.");
uint256 previous = _minTokensBeforeSwap;
_minTokensBeforeSwap = minTokensBeforeSwap_;
emit MinTokensBeforeSwapUpdated(previous, _minTokensBeforeSwap);
}
function setTaxBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner {
require(_autoBurnEnabled, "Auto burn feature must be enabled. Try the EnableAutoBurn function.");
require(taxBurn_ + _taxReward + _taxLiquify < 100, "Tax fee too high.");
uint8 previousTax = _taxBurn;
uint8 previousDecimals = _taxBurnDecimals;
_taxBurn = taxBurn_;
_taxBurnDecimals = taxBurnDecimals_;
emit TaxBurnUpdate(previousTax, previousDecimals, taxBurn_, taxBurnDecimals_);
}
function setTaxReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner {
require(_rewardEnabled, "Reward feature must be enabled. Try the EnableReward function.");
require(_taxBurn + taxReward_ + _taxLiquify < 100, "Tax fee too high.");
uint8 previousTax = _taxReward;
uint8 previousDecimals = _taxRewardDecimals;
_taxReward = taxReward_;
_taxBurnDecimals = taxRewardDecimals_;
emit TaxRewardUpdate(previousTax, previousDecimals, taxReward_, taxRewardDecimals_);
}
function setTaxLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_) public onlyOwner {
require(_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature must be enabled. Try the EnableAutoSwapAndLiquify function.");
require(_taxBurn + _taxReward + taxLiquify_ < 100, "Tax fee too high.");
uint8 previousTax = _taxLiquify;
uint8 previousDecimals = _taxLiquifyDecimals;
_taxLiquify = taxLiquify_;
_taxLiquifyDecimals = taxLiquifyDecimals_;
emit TaxLiquifyUpdate(previousTax, previousDecimals, taxLiquify_, taxLiquifyDecimals_);
}
}
| 4,786,406 | [
1,
19,
10498,
87,
3298,
434,
324,
26488,
364,
1758,
716,
854,
5849,
316,
15847,
19890,
18,
10498,
87,
3298,
434,
324,
26488,
364,
1758,
716,
854,
8845,
628,
15847,
19890,
18,
10498,
87,
3298,
434,
1492,
1758,
854,
8845,
628,
14036,
18,
10498,
87,
3298,
434,
1492,
1758,
854,
8845,
628,
19890,
18,
1922,
526,
434,
6138,
716,
854,
8845,
628,
19890,
18,
4232,
39,
3462,
3155,
8263,
511,
18988,
24237,
2845,
2893,
4633,
1220,
3155,
471,
678,
1584,
44,
3082,
6835,
1758,
18,
12177,
18305,
88,
2430,
854,
3271,
358,
18,
1220,
353,
392,
1758,
716,
1158,
1245,
848,
1240,
2006,
281,
358,
18,
3416,
11366,
434,
5320,
38,
321,
18,
10286,
364,
1240,
5320,
5242,
2353,
404,
9,
18,
3416,
11366,
434,
5320,
17631,
1060,
18,
10286,
364,
1240,
5320,
5242,
2353,
404,
9,
18,
3416,
11366,
434,
5320,
48,
18988,
1164,
18,
10286,
364,
1240,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
4232,
39,
3462,
758,
2242,
367,
814,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
26606,
38,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
2316,
38,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
17631,
1060,
31,
203,
377,
203,
565,
1758,
8526,
3238,
389,
24602,
1265,
17631,
1060,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
2713,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
565,
1758,
2713,
389,
318,
291,
91,
438,
58,
22,
4154,
31,
203,
203,
565,
1758,
3238,
5381,
18305,
3032,
273,
374,
92,
12648,
12648,
12648,
12648,
2787,
72,
41,
69,
40,
31,
203,
377,
203,
3639,
18240,
4993,
273,
261,
67,
8066,
15639,
342,
1728,
636,
67,
8066,
67,
15639,
31809,
13,
5551,
18,
203,
3639,
2457,
3454,
30,
309,
389,
8066,
38,
321,
353,
404,
471,
389,
8066,
38,
321,
31809,
353,
576,
18,
203,
3639,
18240,
4993,
273,
374,
18,
1611,
9,
203,
203,
3639,
971,
1846,
2545,
5320,
4993,
364,
18305,
358,
506,
1381,
9,
364,
3454,
16,
203,
3639,
444,
389,
8066,
38,
321,
358,
1381,
471,
389,
8066,
2
] |
./full_match/4/0x6dE14C9394364C1EE521Ff1Dfc8171A891eB0e88/sources/33c98a9b4e0157d63c8de5d686acc210/MarketplaceSettings.sol | * @title MarketplaceSettings Settings governing the marketplace fees./ Constants State Variables Max wei value within the marketplace Min wei value within the marketplace Percentage fee for the marketplace, 3 == 3% Mapping of ERC721 contract to the primary sale fee. If primary sale fee is 0 for an origin contract then primary sale fee is ignored. 1 == 1%chimera Mapping of ERC721 contract to the secondary sale fee. If secondary sale fee is 0 for an origin contract then secondary sale fee is ignored. 1 == 1% Mapping of ERC721 contract to mapping of token ID to whether the token has been sold before.chimera Mapping of ERC721 contract to mapping of token ID to whether the token is physical or virtual.chimeramapping of ERC721 contract to mapping of NFT holder addresses to store physicalTokens Id's. Constructor | contract MarketplaceSettings is Ownable, AccessControl, IMarketplaceSettings {
using SafeMath for uint256;
bytes32 public constant TOKEN_MARK_ROLE = "TOKEN_MARK_ROLE";
uint256 private maxValue;
uint256 private minValue;
uint8 private marketplaceFeePercentage;
mapping(address => uint8) private primarySaleFees;
mapping(address => uint8) private secondarySaleFees;
mapping(address => mapping(uint256 => bool)) private soldTokens;
mapping(address => mapping(uint256 => bool)) private physicalTokens;
mapping(address => mapping(address => uint256)) private physicalTokensId;
constructor() public {
_setupRole(AccessControl.DEFAULT_ADMIN_ROLE, owner());
grantRole(TOKEN_MARK_ROLE, owner());
}
function grantMarketplaceAccess(address _account) external {
require(
hasRole(AccessControl.DEFAULT_ADMIN_ROLE, msg.sender),
"grantMarketplaceAccess::Must be admin to call method"
);
grantRole(TOKEN_MARK_ROLE, _account);
}
function getMarketplaceMaxValue() external override view returns (uint256) {
return maxValue;
}
function setMarketplaceMaxValue(uint256 _maxValue) external onlyOwner {
maxValue = _maxValue;
}
function getMarketplaceMinValue() external override view returns (uint256) {
return minValue;
}
function setMarketplaceMinValue(uint256 _minValue) external onlyOwner {
minValue = _minValue;
}
function getMarketplaceFeePercentage()
external
override
view
returns (uint8)
{
return marketplaceFeePercentage;
}
function setMarketplaceFeePercentage(uint8 _percentage) external onlyOwner {
require(
_percentage <= 100,
"setMarketplaceFeePercentage::_percentage must be <= 100"
);
marketplaceFeePercentage = _percentage;
}
function calculateMarketplaceFee(uint256 _amount)
external
override
view
returns (uint256)
{
return _amount.mul(marketplaceFeePercentage).div(100);
}
function getERC721ContractPrimarySaleFeePercentage(address _contractAddress)
external
override
view
returns (uint8)
{
return primarySaleFees[_contractAddress];
}
function setERC721ContractPrimarySaleFeePercentage(
address _contractAddress,
uint8 _percentage
) external onlyOwner {
require(
_percentage <= 100,
"setERC721ContractPrimarySaleFeePercentage::_percentage must be <= 100"
);
primarySaleFees[_contractAddress] = _percentage;
}
function calculatePrimarySaleFee(address _contractAddress, uint256 _amount)
external
override
view
returns (uint256)
{
return _amount.mul(primarySaleFees[_contractAddress]).div(100);
}
function getERC721ContractSecondarySaleFeePercentage(address _contractAddress)
external
override
view
returns (uint8)
{
return secondarySaleFees[_contractAddress];
}
function setERC721ContractSecondarySaleFeePercentage(
address _contractAddress,
uint8 _percentage
) external onlyOwner {
require(
_percentage <= 100,
"setERC721ContractSecondarySaleFeePercentage::_percentage must be <= 100"
);
secondarySaleFees[_contractAddress] = _percentage;
}
function calculateSecondarySaleFee(address _contractAddress, uint256 _amount)
external
override
view
returns (uint256)
{
return _amount.mul(secondarySaleFees[_contractAddress]).div(100);
}
function hasERC721TokenSold(address _contractAddress, uint256 _tokenId)
external
override
view
returns (bool)
{
return soldTokens[_contractAddress][_tokenId];
}
function markERC721Token(
address _contractAddress,
uint256 _tokenId,
bool _hasSold
) external override {
require(
hasRole(TOKEN_MARK_ROLE, msg.sender),
"markERC721Token::Must have TOKEN_MARK_ROLE role to call method"
);
soldTokens[_contractAddress][_tokenId] = _hasSold;
}
function markTokensAsSold(
address _originContract,
uint256[] calldata _tokenIds
) external {
require(
hasRole(TOKEN_MARK_ROLE, msg.sender),
"markERC721Token::Must have TOKEN_MARK_ROLE role to call method"
);
require(
_tokenIds.length <= 2000,
"markTokensAsSold::Attempted to mark more than 2000 tokens as sold"
);
for (uint256 i = 0; i < _tokenIds.length; i++) {
soldTokens[_originContract][_tokenIds[i]] = true;
}
}
function markTokensAsSold(
address _originContract,
uint256[] calldata _tokenIds
) external {
require(
hasRole(TOKEN_MARK_ROLE, msg.sender),
"markERC721Token::Must have TOKEN_MARK_ROLE role to call method"
);
require(
_tokenIds.length <= 2000,
"markTokensAsSold::Attempted to mark more than 2000 tokens as sold"
);
for (uint256 i = 0; i < _tokenIds.length; i++) {
soldTokens[_originContract][_tokenIds[i]] = true;
}
}
function isERC721TokenPhysical(address _contractAddress, uint256 _tokenId)
external
view
returns (bool)
{
return physicalTokens[_contractAddress][_tokenId];
}
function markERC721TokenAsPhysical(
address _contractAddress,
uint256 _tokenId,
bool _hasSold
) external
{
require(
hasRole(TOKEN_MARK_ROLE, msg.sender),
"markERC721TokenAsPhysical::Must have TOKEN_MARK_ROLE role to call method"
);
physicalTokens[_contractAddress][_tokenId] = _hasSold;
}
function markTokensAsPhysical(
address _originContract,
uint256[] calldata _tokenIds
) external {
require(
hasRole(TOKEN_MARK_ROLE, msg.sender),
"markTokensAsPhysical::Must have TOKEN_MARK_ROLE role to call method"
);
require(
_tokenIds.length <= 2000,
"markTokensAsPhysical::Attempted to mark more than 2000 tokens as sold"
);
for (uint256 i = 0; i < _tokenIds.length; i++) {
physicalTokens[_originContract][_tokenIds[i]] = true;
}
}
function markTokensAsPhysical(
address _originContract,
uint256[] calldata _tokenIds
) external {
require(
hasRole(TOKEN_MARK_ROLE, msg.sender),
"markTokensAsPhysical::Must have TOKEN_MARK_ROLE role to call method"
);
require(
_tokenIds.length <= 2000,
"markTokensAsPhysical::Attempted to mark more than 2000 tokens as sold"
);
for (uint256 i = 0; i < _tokenIds.length; i++) {
physicalTokens[_originContract][_tokenIds[i]] = true;
}
}
} | 12,343,927 | [
1,
3882,
24577,
2628,
8709,
314,
1643,
2093,
326,
29917,
1656,
281,
18,
19,
5245,
3287,
23536,
4238,
732,
77,
460,
3470,
326,
29917,
5444,
732,
77,
460,
3470,
326,
29917,
21198,
410,
14036,
364,
326,
29917,
16,
890,
422,
890,
9,
9408,
434,
4232,
39,
27,
5340,
6835,
358,
326,
3354,
272,
5349,
14036,
18,
971,
3354,
272,
5349,
14036,
353,
374,
364,
392,
4026,
6835,
1508,
3354,
272,
5349,
14036,
353,
5455,
18,
404,
422,
404,
9,
343,
4417,
69,
9408,
434,
4232,
39,
27,
5340,
6835,
358,
326,
9946,
272,
5349,
14036,
18,
971,
9946,
272,
5349,
14036,
353,
374,
364,
392,
4026,
6835,
1508,
9946,
272,
5349,
14036,
353,
5455,
18,
404,
422,
404,
9,
9408,
434,
4232,
39,
27,
5340,
6835,
358,
2874,
434,
1147,
1599,
358,
2856,
326,
1147,
711,
2118,
272,
1673,
1865,
18,
343,
4417,
69,
9408,
434,
4232,
39,
27,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
6622,
24577,
2628,
353,
14223,
6914,
16,
24349,
16,
467,
3882,
24577,
2628,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
203,
565,
1731,
1578,
1071,
5381,
14275,
67,
12693,
67,
16256,
273,
315,
8412,
67,
12693,
67,
16256,
14432,
203,
203,
203,
565,
2254,
5034,
3238,
18666,
31,
203,
203,
565,
2254,
5034,
3238,
20533,
31,
203,
203,
565,
2254,
28,
3238,
29917,
14667,
16397,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
28,
13,
3238,
3354,
30746,
2954,
281,
31,
203,
377,
203,
565,
2874,
12,
2867,
516,
2254,
28,
13,
3238,
9946,
30746,
2954,
281,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
11890,
5034,
516,
1426,
3719,
3238,
272,
1673,
5157,
31,
203,
377,
203,
565,
2874,
12,
2867,
516,
2874,
12,
11890,
5034,
516,
1426,
3719,
3238,
11640,
5157,
31,
203,
377,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
11640,
5157,
548,
31,
203,
203,
203,
565,
3885,
1435,
1071,
288,
203,
203,
203,
203,
3639,
389,
8401,
2996,
12,
16541,
18,
5280,
67,
15468,
67,
16256,
16,
3410,
10663,
203,
3639,
7936,
2996,
12,
8412,
67,
12693,
67,
16256,
16,
3410,
10663,
203,
565,
289,
203,
203,
565,
445,
7936,
3882,
24577,
1862,
12,
2867,
389,
4631,
13,
3903,
288,
203,
3639,
2583,
12,
203,
5411,
28335,
12,
16541,
18,
5280,
67,
15468,
67,
16256,
16,
1234,
18,
15330,
3631,
203,
5411,
315,
16243,
3882,
24577,
1862,
2866,
10136,
506,
3981,
358,
745,
2
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.3;
// This library allows for secure storage pointers across proxy implementations
// It will return storage pointers based on a hashed name and type string.
library Storage {
// This library follows a pattern which if solidity had higher level
// type or macro support would condense quite a bit.
// Each basic type which does not support storage locations is encoded as
// a struct of the same name capitalized and has functions 'load' and 'set'
// which load the data and set the data respectively.
// All types will have a function of the form 'typename'Ptr('name') -> storage ptr
// which will return a storage version of the type with slot which is the hash of
// the variable name and type string. This pointer allows easy state management between
// upgrades and overrides the default solidity storage slot system.
/// @dev The address type container
struct Address {
address data;
}
/// @notice A function which turns a variable name for a storage address into a storage
/// pointer for its container.
/// @param name the variable name
/// @return data the storage pointer
function addressPtr(string memory name)
internal
pure
returns (Address storage data)
{
bytes32 typehash = keccak256("address");
bytes32 offset = keccak256(abi.encodePacked(typehash, name));
assembly {
data.slot := offset
}
}
/// @notice A function to load an address from the container struct
/// @param input the storage pointer for the container
/// @return the loaded address
function load(Address storage input) internal view returns (address) {
return input.data;
}
/// @notice A function to set the internal field of an address container
/// @param input the storage pointer to the container
/// @param to the address to set the container to
function set(Address storage input, address to) internal {
input.data = to;
}
/// @dev The uint256 type container
struct Uint256 {
uint256 data;
}
/// @notice A function which turns a variable name for a storage uint256 into a storage
/// pointer for its container.
/// @param name the variable name
/// @return data the storage pointer
function uint256Ptr(string memory name)
internal
pure
returns (Uint256 storage data)
{
bytes32 typehash = keccak256("uint256");
bytes32 offset = keccak256(abi.encodePacked(typehash, name));
assembly {
data.slot := offset
}
}
/// @notice A function to load an uint256 from the container struct
/// @param input the storage pointer for the container
/// @return the loaded uint256
function load(Uint256 storage input) internal view returns (uint256) {
return input.data;
}
/// @notice A function to set the internal field of a unit256 container
/// @param input the storage pointer to the container
/// @param to the address to set the container to
function set(Uint256 storage input, uint256 to) internal {
input.data = to;
}
/// @notice Returns the storage pointer for a named mapping of address to uint256
/// @param name the variable name for the pointer
/// @return data the mapping pointer
function mappingAddressToUnit256Ptr(string memory name)
internal
pure
returns (mapping(address => uint256) storage data)
{
bytes32 typehash = keccak256("mapping(address => uint256)");
bytes32 offset = keccak256(abi.encodePacked(typehash, name));
assembly {
data.slot := offset
}
}
/// @notice Returns the storage pointer for a named mapping of address to uint256[]
/// @param name the variable name for the pointer
/// @return data the mapping pointer
function mappingAddressToUnit256ArrayPtr(string memory name)
internal
pure
returns (mapping(address => uint256[]) storage data)
{
bytes32 typehash = keccak256("mapping(address => uint256[])");
bytes32 offset = keccak256(abi.encodePacked(typehash, name));
assembly {
data.slot := offset
}
}
/// @notice Allows external users to calculate the slot given by this lib
/// @param typeString the string which encodes the type
/// @param name the variable name
/// @return the slot assigned by this lib
function getPtr(string memory typeString, string memory name)
external
pure
returns (uint256)
{
bytes32 typehash = keccak256(abi.encodePacked(typeString));
bytes32 offset = keccak256(abi.encodePacked(typehash, name));
return (uint256)(offset);
}
// A struct which represents 1 packed storage location with a compressed
// address and uint96 pair
struct AddressUint {
address who;
uint96 amount;
}
/// @notice Returns the storage pointer for a named mapping of address to uint256[]
/// @param name the variable name for the pointer
/// @return data the mapping pointer
function mappingAddressToPackedAddressUint(string memory name)
internal
pure
returns (mapping(address => AddressUint) storage data)
{
bytes32 typehash = keccak256("mapping(address => AddressUint)");
bytes32 offset = keccak256(abi.encodePacked(typehash, name));
assembly {
data.slot := offset
}
}
}
| @notice Allows external users to calculate the slot given by this lib @param typeString the string which encodes the type @param name the variable name @return the slot assigned by this lib | function getPtr(string memory typeString, string memory name)
external
pure
returns (uint256)
{
bytes32 typehash = keccak256(abi.encodePacked(typeString));
bytes32 offset = keccak256(abi.encodePacked(typehash, name));
return (uint256)(offset);
}
| 6,479,038 | [
1,
19132,
3903,
3677,
358,
4604,
326,
4694,
864,
635,
333,
2561,
225,
618,
780,
326,
533,
1492,
16834,
326,
618,
225,
508,
326,
2190,
508,
327,
326,
4694,
6958,
635,
333,
2561,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1689,
313,
12,
1080,
3778,
618,
780,
16,
533,
3778,
508,
13,
203,
3639,
3903,
203,
3639,
16618,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
1731,
1578,
618,
2816,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
723,
780,
10019,
203,
3639,
1731,
1578,
1384,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
723,
2816,
16,
508,
10019,
203,
3639,
327,
261,
11890,
5034,
21433,
3348,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "../../interfaces/IERC20.sol";
/**
@author Tellor Inc.
@title TellorFlex
@dev This is a streamlined Tellor oracle system which handles staking, reporting,
* slashing, and user data getters in one contract. This contract is controlled
* by a single address known as 'governance', which could be an externally owned
* account or a contract, allowing for a flexible, modular design.
*/
contract TellorFlex {
IERC20 public token;
address public governance;
uint256 public stakeAmount; //amount required to be a staker
uint256 public totalStakeAmount; //total amount of tokens locked in contract (via stake)
uint256 public reportingLock; // base amount of time before a reporter is able to submit a value again
uint256 public timeOfLastNewValue = block.timestamp; // time of the last new submitted value, originally set to the block timestamp
mapping(bytes32 => Report) private reports; // mapping of query IDs to a report
mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info
// Structs
struct Report {
uint256[] timestamps; // array of all newValueTimestamps reported
mapping(uint256 => uint256) timestampIndex; // mapping of timestamps to respective indices
mapping(uint256 => uint256) timestampToBlockNum; // mapping of timestamp to block number
mapping(uint256 => bytes) valueByTimestamp; // mapping of timestamps to values
mapping(uint256 => address) reporterByTimestamp; // mapping of timestamps to reporters
}
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
mapping(bytes32 => uint256) reportsSubmittedByQueryId;
}
// Events
event NewGovernanceAddress(address _newGovernanceAddress);
event NewReport(
bytes32 _queryId,
uint256 _time,
bytes _value,
uint256 _nonce,
bytes _queryData,
address _reporter
);
event NewReportingLock(uint256 _newReportingLock);
event NewStakeAmount(uint256 _newStakeAmount);
event NewStaker(address _staker, uint256 _amount);
event ReporterSlashed(
address _reporter,
address _recipient,
uint256 _slashAmount
);
event StakeWithdrawRequested(address _staker, uint256 _amount);
event StakeWithdrawn(address _staker);
event ValueRemoved(bytes32 _queryId, uint256 _timestamp);
/**
* @dev Initializes system parameters
* @param _token address of token used for staking
* @param _governance address which controls system
* @param _stakeAmount amount of token needed to report oracle values
* @param _reportingLock base amount of time (seconds) before reporter is able to report again
*/
constructor(
address _token,
address _governance,
uint256 _stakeAmount,
uint256 _reportingLock
) {
require(_token != address(0), "must set token address");
require(_governance != address(0), "must set governance address");
token = IERC20(_token);
governance = _governance;
stakeAmount = _stakeAmount;
reportingLock = _reportingLock;
}
/**
* @dev Changes governance address
* @param _newGovernanceAddress new governance address
*/
function changeGovernanceAddress(address _newGovernanceAddress) external {
require(msg.sender == governance, "caller must be governance address");
require(
_newGovernanceAddress != address(0),
"must set governance address"
);
governance = _newGovernanceAddress;
emit NewGovernanceAddress(_newGovernanceAddress);
}
/**
* @dev Changes base amount of time (seconds) before reporter is allowed to report again
* @param _newReportingLock new reporter lock time in seconds
*/
function changeReportingLock(uint256 _newReportingLock) external {
require(msg.sender == governance, "caller must be governance address");
require(
_newReportingLock > 0,
"reporting lock must be greater than zero"
);
reportingLock = _newReportingLock;
emit NewReportingLock(_newReportingLock);
}
/**
* @dev Changes amount of token stake required to report values
* @param _newStakeAmount new reporter stake amount
*/
function changeStakeAmount(uint256 _newStakeAmount) external {
require(msg.sender == governance, "caller must be governance address");
require(_newStakeAmount > 0, "stake amount must be greater than zero");
stakeAmount = _newStakeAmount;
emit NewStakeAmount(_newStakeAmount);
}
/**
* @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(
token.transferFrom(
msg.sender,
address(this),
_amount - _staker.lockedBalance
)
);
_staker.lockedBalance = 0;
}
} else {
require(token.transferFrom(msg.sender, address(this), _amount));
}
_staker.startDate = block.timestamp; // This resets their stake start date to now
_staker.stakedBalance += _amount;
totalStakeAmount += _amount;
emit NewStaker(msg.sender, _amount);
}
/**
* @dev Removes a value from the oracle.
* Note: this function is only callable by the Governance contract.
* @param _queryId is ID of the specific data feed
* @param _timestamp is the timestamp of the data value to remove
*/
function removeValue(bytes32 _queryId, uint256 _timestamp) external {
require(msg.sender == governance, "caller must be governance address");
Report storage rep = reports[_queryId];
uint256 _index = rep.timestampIndex[_timestamp];
require(_timestamp == rep.timestamps[_index], "invalid timestamp");
// Shift all timestamps back to reflect deletion of value
for (uint256 _i = _index; _i < rep.timestamps.length - 1; _i++) {
rep.timestamps[_i] = rep.timestamps[_i + 1];
rep.timestampIndex[rep.timestamps[_i]] -= 1;
}
// Delete and reset timestamp and value
delete rep.timestamps[rep.timestamps.length - 1];
rep.timestamps.pop();
rep.valueByTimestamp[_timestamp] = "";
rep.timestampIndex[_timestamp] = 0;
emit ValueRemoved(_queryId, _timestamp);
}
/**
* @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;
totalStakeAmount -= _amount;
emit StakeWithdrawRequested(msg.sender, _amount);
}
/**
* @dev Slashes a reporter and transfers their stake amount to the given recipient
* Note: this function is only callable by the governance address.
* @param _reporter is the address of the reporter being slashed
* @param _recipient is the address receiving the reporter's stake
* @return uint256 amount of token slashed and sent to recipient address
*/
function slashReporter(address _reporter, address _recipient)
external
returns (uint256)
{
require(msg.sender == governance, "only governance can slash reporter");
StakeInfo storage _staker = stakerDetails[_reporter];
require(
_staker.stakedBalance + _staker.lockedBalance > 0,
"zero staker balance"
);
uint256 _slashAmount;
if (_staker.lockedBalance >= stakeAmount) {
_slashAmount = stakeAmount;
_staker.lockedBalance -= stakeAmount;
} else if (
_staker.lockedBalance + _staker.stakedBalance >= stakeAmount
) {
_slashAmount = stakeAmount;
_staker.stakedBalance -= stakeAmount - _staker.lockedBalance;
totalStakeAmount -= stakeAmount - _staker.lockedBalance;
_staker.lockedBalance = 0;
} else {
_slashAmount = _staker.stakedBalance + _staker.lockedBalance;
totalStakeAmount -= _staker.stakedBalance;
_staker.stakedBalance = 0;
_staker.lockedBalance = 0;
}
token.transfer(_recipient, _slashAmount);
emit ReporterSlashed(_reporter, _recipient, _slashAmount);
return (_slashAmount);
}
/**
* @dev Allows a reporter to submit a value to the oracle
* @param _queryId is ID of the specific data feed. Equals keccak256(_queryData) for non-legacy IDs
* @param _value is the value the user submits to the oracle
* @param _nonce is the current value count for the query id
* @param _queryData is the data used to fulfill the data query
*/
function submitValue(
bytes32 _queryId,
bytes calldata _value,
uint256 _nonce,
bytes memory _queryData
) external {
Report storage rep = reports[_queryId];
require(
_nonce == rep.timestamps.length || _nonce == 0,
"nonce must match timestamp index"
);
StakeInfo storage _staker = stakerDetails[msg.sender];
require(
_staker.stakedBalance >= stakeAmount,
"balance must be greater than stake amount"
);
// Require reporter to abide by given reporting lock
require(
(block.timestamp - _staker.reporterLastTimestamp) * 1000 >
(reportingLock * 1000) / (_staker.stakedBalance / stakeAmount),
"still in reporter time lock, please wait!"
);
require(
_queryId == keccak256(_queryData) || uint256(_queryId) <= 100,
"id must be hash of bytes data"
);
_staker.reporterLastTimestamp = block.timestamp;
// Checks for no double reporting of timestamps
require(
rep.reporterByTimestamp[block.timestamp] == address(0),
"timestamp already reported for"
);
// Update number of timestamps, value for given timestamp, and reporter for timestamp
rep.timestampIndex[block.timestamp] = rep.timestamps.length;
rep.timestamps.push(block.timestamp);
rep.timestampToBlockNum[block.timestamp] = block.number;
rep.valueByTimestamp[block.timestamp] = _value;
rep.reporterByTimestamp[block.timestamp] = msg.sender;
// Update last oracle value and number of values submitted by a reporter
timeOfLastNewValue = block.timestamp;
_staker.reportsSubmitted++;
_staker.reportsSubmittedByQueryId[_queryId]++;
emit NewReport(
_queryId,
block.timestamp,
_value,
_nonce,
_queryData,
msg.sender
);
}
/**
* @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");
token.transfer(msg.sender, _s.lockedBalance);
_s.lockedBalance = 0;
emit StakeWithdrawn(msg.sender);
}
//Getters
/**
* @dev Returns the block number at a given timestamp
* @param _queryId is ID of the specific data feed
* @param _timestamp is the timestamp to find the corresponding block number for
* @return uint256 block number of the timestamp for the given data ID
*/
function getBlockNumberByTimestamp(bytes32 _queryId, uint256 _timestamp)
external
view
returns (uint256)
{
return reports[_queryId].timestampToBlockNum[_timestamp];
}
/**
* @dev Returns the current value of a data feed given a specific ID
* @param _queryId is the ID of the specific data feed
* @return bytes memory of the current value of data
*/
function getCurrentValue(bytes32 _queryId)
external
view
returns (bytes memory)
{
return
reports[_queryId].valueByTimestamp[
reports[_queryId].timestamps[
reports[_queryId].timestamps.length - 1
]
];
}
/**
* @dev Returns governance address
* @return address governance
*/
function getGovernanceAddress() external view returns (address) {
return governance;
}
/**
* @dev Counts the number of values that have been submitted for the request.
* @param _queryId the id to look up
* @return uint256 count of the number of values received for the id
*/
function getNewValueCountbyQueryId(bytes32 _queryId)
external
view
returns (uint256)
{
return reports[_queryId].timestamps.length;
}
/**
* @dev Returns reporter address and whether a value was removed for a given queryId and timestamp
* @param _queryId the id to look up
* @param _timestamp is the timestamp of the value to look up
* @return address reporter who submitted the value
* @return bool true if the value was removed
*/
function getReportDetails(bytes32 _queryId, uint256 _timestamp)
external
view
returns (address, bool)
{
bool _wasRemoved = reports[_queryId].timestampIndex[_timestamp] == 0 &&
keccak256(reports[_queryId].valueByTimestamp[_timestamp]) ==
keccak256(bytes("")) &&
reports[_queryId].reporterByTimestamp[_timestamp] != address(0);
return (reports[_queryId].reporterByTimestamp[_timestamp], _wasRemoved);
}
/**
* @dev Returns the address of the reporter who submitted a value for a data ID at a specific time
* @param _queryId is ID of the specific data feed
* @param _timestamp is the timestamp to find a corresponding reporter for
* @return address of the reporter who reported the value for the data ID at the given timestamp
*/
function getReporterByTimestamp(bytes32 _queryId, uint256 _timestamp)
external
view
returns (address)
{
return reports[_queryId].reporterByTimestamp[_timestamp];
}
/**
* @dev Returns the timestamp of the reporter's last submission
* @param _reporter is address of the reporter
* @return uint256 timestamp of the reporter's last submission
*/
function getReporterLastTimestamp(address _reporter)
external
view
returns (uint256)
{
return stakerDetails[_reporter].reporterLastTimestamp;
}
/**
* @dev Returns the reporting lock time, the amount of time a reporter must wait to submit again
* @return uint256 reporting lock time
*/
function getReportingLock() external view returns (uint256) {
return reportingLock;
}
/**
* @dev Returns the number of values submitted by a specific reporter address
* @param _reporter is the address of a reporter
* @return uint256 of the number of values submitted by the given reporter
*/
function getReportsSubmittedByAddress(address _reporter)
external
view
returns (uint256)
{
return stakerDetails[_reporter].reportsSubmitted;
}
/**
* @dev Returns the number of values submitted to a specific queryId by a specific reporter address
* @param _reporter is the address of a reporter
* @param _queryId is the ID of the specific data feed
* @return uint256 of the number of values submitted by the given reporter to the given queryId
*/
function getReportsSubmittedByAddressAndQueryId(
address _reporter,
bytes32 _queryId
) external view returns (uint256) {
return stakerDetails[_reporter].reportsSubmittedByQueryId[_queryId];
}
/**
* @dev Returns amount required to report oracle values
* @return uint256 stake amount
*/
function getStakeAmount() external view returns (uint256) {
return stakeAmount;
}
/**
* @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
);
}
/**
* @dev Returns the timestamp for the last value of any ID from the oracle
* @return uint256 of timestamp of the last oracle value
*/
function getTimeOfLastNewValue() external view returns (uint256) {
return timeOfLastNewValue;
}
/**
* @dev Gets the timestamp for the value based on their index
* @param _queryId is the id to look up
* @param _index is the value index to look up
* @return uint256 timestamp
*/
function getTimestampbyQueryIdandIndex(bytes32 _queryId, uint256 _index)
external
view
returns (uint256)
{
return reports[_queryId].timestamps[_index];
}
/**
* @dev Returns the index of a reporter timestamp in the timestamp array for a specific data ID
* @param _queryId is ID of the specific data feed
* @param _timestamp is the timestamp to find in the timestamps array
* @return uint256 of the index of the reporter timestamp in the array for specific ID
*/
function getTimestampIndexByTimestamp(bytes32 _queryId, uint256 _timestamp)
external
view
returns (uint256)
{
return reports[_queryId].timestampIndex[_timestamp];
}
/**
* @dev Returns the address of the token used for staking
* @return address of the token used for staking
*/
function getTokenAddress() external view returns (address) {
return address(token);
}
/**
* @dev Returns total amount of token staked for reporting
* @return uint256 total amount of token staked
*/
function getTotalStakeAmount() external view returns (uint256) {
return totalStakeAmount;
}
/**
* @dev Retrieve value from oracle based on timestamp
* @param _queryId being requested
* @param _timestamp to retrieve data/value from
* @return bytes value for timestamp submitted
*/
function retrieveData(bytes32 _queryId, uint256 _timestamp)
external
view
returns (bytes memory)
{
return reports[_queryId].valueByTimestamp[_timestamp];
}
}
| * @dev Gets the timestamp for the value based on their index @param _queryId is the id to look up @param _index is the value index to look up @return uint256 timestamp/ | function getTimestampbyQueryIdandIndex(bytes32 _queryId, uint256 _index)
external
view
returns (uint256)
{
return reports[_queryId].timestamps[_index];
}
| 12,900,971 | [
1,
3002,
326,
2858,
364,
326,
460,
2511,
603,
3675,
770,
225,
389,
2271,
548,
353,
326,
612,
358,
2324,
731,
225,
389,
1615,
353,
326,
460,
770,
358,
2324,
731,
327,
2254,
5034,
2858,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
11940,
1637,
1138,
548,
464,
1016,
12,
3890,
1578,
389,
2271,
548,
16,
2254,
5034,
389,
1615,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
327,
10557,
63,
67,
2271,
548,
8009,
25459,
63,
67,
1615,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x1ea36E48689c4345cFcd5f76a53A09CFb770aA90/sources/contracts/staking.sol | Helper function to convert addresses to strings | function addressToString(
address _address
) internal pure returns (string memory) {
bytes32 value = bytes32(uint256(uint160(_address)));
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(42);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < 20; i++) {
str[2 + i * 2] = alphabet[uint256(uint8(value[i + 12] >> 4))];
str[3 + i * 2] = alphabet[uint256(uint8(value[i + 12] & 0x0f))];
}
return string(str);
}
| 5,597,994 | [
1,
2276,
445,
358,
1765,
6138,
358,
2064,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1758,
5808,
12,
203,
3639,
1758,
389,
2867,
203,
565,
262,
2713,
16618,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
1731,
1578,
460,
273,
1731,
1578,
12,
11890,
5034,
12,
11890,
16874,
24899,
2867,
3719,
1769,
203,
3639,
1731,
3778,
10877,
273,
315,
26684,
28953,
14432,
203,
203,
3639,
1731,
3778,
609,
273,
394,
1731,
12,
9452,
1769,
203,
3639,
609,
63,
20,
65,
273,
315,
20,
14432,
203,
3639,
609,
63,
21,
65,
273,
315,
92,
14432,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
4200,
31,
277,
27245,
288,
203,
5411,
609,
63,
22,
397,
277,
380,
576,
65,
273,
10877,
63,
11890,
5034,
12,
11890,
28,
12,
1132,
63,
77,
397,
2593,
65,
1671,
1059,
3719,
15533,
203,
5411,
609,
63,
23,
397,
277,
380,
576,
65,
273,
10877,
63,
11890,
5034,
12,
11890,
28,
12,
1132,
63,
77,
397,
2593,
65,
473,
374,
92,
20,
74,
3719,
15533,
203,
3639,
289,
203,
203,
3639,
327,
533,
12,
701,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
contract DataSourceInterface {
function isDataSource() public pure returns (bool);
function getGroupResult(uint matchId) external;
function getRoundOfSixteenTeams(uint index) external;
function getRoundOfSixteenResult(uint matchId) external;
function getQuarterResult(uint matchId) external;
function getSemiResult(uint matchId) external;
function getFinalTeams() external;
function getYellowCards() external;
function getRedCards() external;
}
/**
* @title DataLayer.
* @author CryptoCup Team (https://cryptocup.io/about)
*/
contract DataLayer{
uint256 constant WCCTOKEN_CREATION_LIMIT = 5000000;
uint256 constant STARTING_PRICE = 45 finney;
/// Epoch times based on when the prices change.
uint256 constant FIRST_PHASE = 1527476400;
uint256 constant SECOND_PHASE = 1528081200;
uint256 constant THIRD_PHASE = 1528686000;
uint256 constant WORLD_CUP_START = 1528945200;
DataSourceInterface public dataSource;
address public dataSourceAddress;
address public adminAddress;
uint256 public deploymentTime = 0;
uint256 public gameFinishedTime = 0; //set this to now when oraclize was called.
uint32 public lastCalculatedToken = 0;
uint256 public pointsLimit = 0;
uint32 public lastCheckedToken = 0;
uint32 public winnerCounter = 0;
uint32 public lastAssigned = 0;
uint256 public auxWorstPoints = 500000000;
uint32 public payoutRange = 0;
uint32 public lastPrizeGiven = 0;
uint256 public prizePool = 0;
uint256 public adminPool = 0;
uint256 public finalizedTime = 0;
enum teamState { None, ROS, QUARTERS, SEMIS, FINAL }
enum pointsValidationState { Unstarted, LimitSet, LimitCalculated, OrderChecked, TopWinnersAssigned, WinnersAssigned, Finished }
/**
* groups1 scores of the first half of matches (8 bits each)
* groups2 scores of the second half of matches (8 bits each)
* brackets winner's team ids of each round (5 bits each)
* timeStamp creation timestamp
* extra number of yellow and red cards (16 bits each)
*/
struct Token {
uint192 groups1;
uint192 groups2;
uint160 brackets;
uint64 timeStamp;
uint32 extra;
}
struct GroupResult{
uint8 teamOneGoals;
uint8 teamTwoGoals;
}
struct BracketPhase{
uint8[16] roundOfSixteenTeamsIds;
mapping (uint8 => bool) teamExists;
mapping (uint8 => teamState) middlePhaseTeamsIds;
uint8[4] finalsTeamsIds;
}
struct Extras {
uint16 yellowCards;
uint16 redCards;
}
// List of all tokens
Token[] tokens;
GroupResult[48] groupsResults;
BracketPhase bracketsResults;
Extras extraResults;
// List of all tokens that won
uint256[] sortedWinners;
// List of the worst tokens (they also win)
uint256[] worstTokens;
pointsValidationState public pValidationState = pointsValidationState.Unstarted;
mapping (address => uint256[]) public tokensOfOwnerMap;
mapping (uint256 => address) public ownerOfTokenMap;
mapping (uint256 => address) public tokensApprovedMap;
mapping (uint256 => uint256) public tokenToPayoutMap;
mapping (uint256 => uint16) public tokenToPointsMap;
event LogTokenBuilt(address creatorAddress, uint256 tokenId, Token token);
event LogDataSourceCallbackList(uint8[] result);
event LogDataSourceCallbackInt(uint8 result);
event LogDataSourceCallbackTwoInt(uint8 result, uint8 result2);
}
///Author Dieter Shirley (https://github.com/dete)
contract ERC721 {
event LogTransfer(address from, address to, uint256 tokenId);
event LogApproval(address owner, address approved, uint256 tokenId);
function name() public view returns (string);
function symbol() public view returns (string);
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
}
/**
* @title AccessControlLayer
* @author CryptoCup Team (https://cryptocup.io/about)
* @dev Containes basic admin modifiers to restrict access to some functions. Allows
* for pauseing, and setting emergency stops.
*/
contract AccessControlLayer is DataLayer{
bool public paused = false;
bool public finalized = false;
bool public saleOpen = true;
/**
* @dev Main modifier to limit access to delicate functions.
*/
modifier onlyAdmin() {
require(msg.sender == adminAddress);
_;
}
/**
* @dev Modifier that checks that the contract is not paused
*/
modifier isNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier that checks that the contract is paused
*/
modifier isPaused() {
require(paused);
_;
}
/**
* @dev Modifier that checks that the contract has finished successfully
*/
modifier hasFinished() {
require((gameFinishedTime != 0) && now >= (gameFinishedTime + (15 days)));
_;
}
/**
* @dev Modifier that checks that the contract has finalized
*/
modifier hasFinalized() {
require(finalized);
_;
}
/**
* @dev Checks if pValidationState is in the provided stats
* @param state State required to run
*/
modifier checkState(pointsValidationState state){
require(pValidationState == state);
_;
}
/**
* @dev Transfer contract's ownership
* @param _newAdmin Address to be set
*/
function setAdmin(address _newAdmin) external onlyAdmin {
require(_newAdmin != address(0));
adminAddress = _newAdmin;
}
/**
* @dev Sets the contract pause state
* @param state True to pause
*/
function setPauseState(bool state) external onlyAdmin {
paused = state;
}
/**
* @dev Sets the contract to finalized
* @param state True to finalize
*/
function setFinalized(bool state) external onlyAdmin {
paused = state;
finalized = state;
if(finalized == true)
finalizedTime = now;
}
}
/**
* @title CryptoCupToken, main implemantations of the ERC721 standard
* @author CryptoCup Team (https://cryptocup.io/about)
*/
contract CryptocupToken is AccessControlLayer, ERC721 {
//FUNCTIONALTIY
/**
* @notice checks if a user owns a token
* @param userAddress - The address to check.
* @param tokenId - ID of the token that needs to be verified.
* @return true if the userAddress provided owns the token.
*/
function _userOwnsToken(address userAddress, uint256 tokenId) internal view returns (bool){
return ownerOfTokenMap[tokenId] == userAddress;
}
/**
* @notice checks if the address provided is approved for a given token
* @param userAddress
* @param tokenId
* @return true if it is aproved
*/
function _tokenIsApproved(address userAddress, uint256 tokenId) internal view returns (bool) {
return tokensApprovedMap[tokenId] == userAddress;
}
/**
* @notice transfers the token specified from sneder address to receiver address.
* @param fromAddress the sender address that initially holds the token.
* @param toAddress the receipient of the token.
* @param tokenId ID of the token that will be sent.
*/
function _transfer(address fromAddress, address toAddress, uint256 tokenId) internal {
require(tokensOfOwnerMap[toAddress].length < 100);
require(pValidationState == pointsValidationState.Unstarted);
tokensOfOwnerMap[toAddress].push(tokenId);
ownerOfTokenMap[tokenId] = toAddress;
uint256[] storage tokenArray = tokensOfOwnerMap[fromAddress];
for (uint256 i = 0; i < tokenArray.length; i++){
if(tokenArray[i] == tokenId){
tokenArray[i] = tokenArray[tokenArray.length-1];
}
}
delete tokenArray[tokenArray.length-1];
tokenArray.length--;
delete tokensApprovedMap[tokenId];
}
/**
* @notice Approve the address for a given token
* @param tokenId - ID of token to be approved
* @param userAddress - Address that will be approved
*/
function _approve(uint256 tokenId, address userAddress) internal {
tokensApprovedMap[tokenId] = userAddress;
}
/**
* @notice set token owner to an address
* @dev sets token owner on the contract data structures
* @param ownerAddress address to be set
* @param tokenId Id of token to be used
*/
function _setTokenOwner(address ownerAddress, uint256 tokenId) internal{
tokensOfOwnerMap[ownerAddress].push(tokenId);
ownerOfTokenMap[tokenId] = ownerAddress;
}
//ERC721 INTERFACE
function name() public view returns (string){
return "Cryptocup";
}
function symbol() public view returns (string){
return "CC";
}
function balanceOf(address userAddress) public view returns (uint256 count) {
return tokensOfOwnerMap[userAddress].length;
}
function transfer(address toAddress,uint256 tokenId) external isNotPaused {
require(toAddress != address(0));
require(toAddress != address(this));
require(_userOwnsToken(msg.sender, tokenId));
_transfer(msg.sender, toAddress, tokenId);
LogTransfer(msg.sender, toAddress, tokenId);
}
function transferFrom(address fromAddress, address toAddress, uint256 tokenId) external isNotPaused {
require(toAddress != address(0));
require(toAddress != address(this));
require(_tokenIsApproved(msg.sender, tokenId));
require(_userOwnsToken(fromAddress, tokenId));
_transfer(fromAddress, toAddress, tokenId);
LogTransfer(fromAddress, toAddress, tokenId);
}
function approve( address toAddress, uint256 tokenId) external isNotPaused {
require(toAddress != address(0));
require(_userOwnsToken(msg.sender, tokenId));
_approve(tokenId, toAddress);
LogApproval(msg.sender, toAddress, tokenId);
}
function totalSupply() public view returns (uint) {
return tokens.length;
}
function ownerOf(uint256 tokenId) external view returns (address ownerAddress) {
ownerAddress = ownerOfTokenMap[tokenId];
require(ownerAddress != address(0));
}
function tokensOfOwner(address ownerAddress) external view returns(uint256[] tokenIds) {
tokenIds = tokensOfOwnerMap[ownerAddress];
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev 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 GameLogicLayer, contract in charge of everything related to calculating points, asigning
* winners, and distributing prizes.
* @author CryptoCup Team (https://cryptocup.io/about)
*/
contract GameLogicLayer is CryptocupToken{
using SafeMath for *;
uint8 TEAM_RESULT_MASK_GROUPS = 15;
uint160 RESULT_MASK_BRACKETS = 31;
uint16 EXTRA_MASK_BRACKETS = 65535;
uint16 private lastPosition;
uint16 private superiorQuota;
uint16[] private payDistributionAmount = [1,1,1,1,1,1,1,1,1,1,5,5,10,20,50,100,100,200,500,1500,2500];
uint32[] private payoutDistribution;
event LogGroupDataArrived(uint matchId, uint8 result, uint8 result2);
event LogRoundOfSixteenArrived(uint id, uint8 result);
event LogMiddlePhaseArrived(uint matchId, uint8 result);
event LogFinalsArrived(uint id, uint8[4] result);
event LogExtrasArrived(uint id, uint16 result);
//ORACLIZE
function dataSourceGetGroupResult(uint matchId) external onlyAdmin{
dataSource.getGroupResult(matchId);
}
function dataSourceGetRoundOfSixteen(uint index) external onlyAdmin{
dataSource.getRoundOfSixteenTeams(index);
}
function dataSourceGetRoundOfSixteenResult(uint matchId) external onlyAdmin{
dataSource.getRoundOfSixteenResult(matchId);
}
function dataSourceGetQuarterResult(uint matchId) external onlyAdmin{
dataSource.getQuarterResult(matchId);
}
function dataSourceGetSemiResult(uint matchId) external onlyAdmin{
dataSource.getSemiResult(matchId);
}
function dataSourceGetFinals() external onlyAdmin{
dataSource.getFinalTeams();
}
function dataSourceGetYellowCards() external onlyAdmin{
dataSource.getYellowCards();
}
function dataSourceGetRedCards() external onlyAdmin{
dataSource.getRedCards();
}
/**
* @notice sets a match result to the contract storage
* @param matchId id of match to check
* @param result number of goals the first team scored
* @param result2 number of goals the second team scored
*/
function dataSourceCallbackGroup(uint matchId, uint8 result, uint8 result2) public {
require (msg.sender == dataSourceAddress);
require (matchId >= 0 && matchId <= 47);
groupsResults[matchId].teamOneGoals = result;
groupsResults[matchId].teamTwoGoals = result2;
LogGroupDataArrived(matchId, result, result2);
}
/**
* @notice sets the sixteen teams that made it through groups to the contract storage
* @param id index of sixteen teams
* @param result results to be set
*/
function dataSourceCallbackRoundOfSixteen(uint id, uint8 result) public {
require (msg.sender == dataSourceAddress);
bracketsResults.roundOfSixteenTeamsIds[id] = result;
bracketsResults.teamExists[result] = true;
LogRoundOfSixteenArrived(id, result);
}
function dataSourceCallbackTeamId(uint matchId, uint8 result) public {
require (msg.sender == dataSourceAddress);
teamState state = bracketsResults.middlePhaseTeamsIds[result];
if (matchId >= 48 && matchId <= 55){
if (state < teamState.ROS)
bracketsResults.middlePhaseTeamsIds[result] = teamState.ROS;
} else if (matchId >= 56 && matchId <= 59){
if (state < teamState.QUARTERS)
bracketsResults.middlePhaseTeamsIds[result] = teamState.QUARTERS;
} else if (matchId == 60 || matchId == 61){
if (state < teamState.SEMIS)
bracketsResults.middlePhaseTeamsIds[result] = teamState.SEMIS;
}
LogMiddlePhaseArrived(matchId, result);
}
/**
* @notice sets the champion, second, third and fourth teams to the contract storage
* @param id
* @param result ids of the four teams
*/
function dataSourceCallbackFinals(uint id, uint8[4] result) public {
require (msg.sender == dataSourceAddress);
uint256 i;
for(i = 0; i < 4; i++){
bracketsResults.finalsTeamsIds[i] = result[i];
}
LogFinalsArrived(id, result);
}
/**
* @notice sets the number of cards to the contract storage
* @param id 101 for yellow cards, 102 for red cards
* @param result amount of cards
*/
function dataSourceCallbackExtras(uint id, uint16 result) public {
require (msg.sender == dataSourceAddress);
if (id == 101){
extraResults.yellowCards = result;
} else if (id == 102){
extraResults.redCards = result;
}
LogExtrasArrived(id, result);
}
/**
* @notice check if prediction for a match winner is correct
* @param realResultOne amount of goals team one scored
* @param realResultTwo amount of goals team two scored
* @param tokenResultOne amount of goals team one was predicted to score
* @param tokenResultTwo amount of goals team two was predicted to score
* @return
*/
function matchWinnerOk(uint8 realResultOne, uint8 realResultTwo, uint8 tokenResultOne, uint8 tokenResultTwo) internal pure returns(bool){
int8 realR = int8(realResultOne - realResultTwo);
int8 tokenR = int8(tokenResultOne - tokenResultTwo);
return (realR > 0 && tokenR > 0) || (realR < 0 && tokenR < 0) || (realR == 0 && tokenR == 0);
}
/**
* @notice get points from a single match
* @param matchIndex
* @param groupsPhase token predictions
* @return 10 if predicted score correctly, 3 if predicted only who would win
* and 0 if otherwise
*/
function getMatchPointsGroups (uint256 matchIndex, uint192 groupsPhase) internal view returns(uint16 matchPoints) {
uint8 tokenResultOne = uint8(groupsPhase & TEAM_RESULT_MASK_GROUPS);
uint8 tokenResultTwo = uint8((groupsPhase >> 4) & TEAM_RESULT_MASK_GROUPS);
uint8 teamOneGoals = groupsResults[matchIndex].teamOneGoals;
uint8 teamTwoGoals = groupsResults[matchIndex].teamTwoGoals;
if (teamOneGoals == tokenResultOne && teamTwoGoals == tokenResultTwo){
matchPoints += 10;
} else {
if (matchWinnerOk(teamOneGoals, teamTwoGoals, tokenResultOne, tokenResultTwo)){
matchPoints += 3;
}
}
}
/**
* @notice calculates points from the last two matches
* @param brackets token predictions
* @return amount of points gained from the last two matches
*/
function getFinalRoundPoints (uint160 brackets) internal view returns(uint16 finalRoundPoints) {
uint8[3] memory teamsIds;
for (uint i = 0; i <= 2; i++){
brackets = brackets >> 5; //discard 4th place
teamsIds[2-i] = uint8(brackets & RESULT_MASK_BRACKETS);
}
if (teamsIds[0] == bracketsResults.finalsTeamsIds[0]){
finalRoundPoints += 100;
}
if (teamsIds[2] == bracketsResults.finalsTeamsIds[2]){
finalRoundPoints += 25;
}
if (teamsIds[0] == bracketsResults.finalsTeamsIds[1]){
finalRoundPoints += 50;
}
if (teamsIds[1] == bracketsResults.finalsTeamsIds[0] || teamsIds[1] == bracketsResults.finalsTeamsIds[1]){
finalRoundPoints += 50;
}
}
/**
* @notice calculates points for round of sixteen, quarter-finals and semifinals
* @param size amount of matches in round
* @param round ros, qf, sf or f
* @param brackets predictions
* @return amount of points
*/
function getMiddleRoundPoints(uint8 size, teamState round, uint160 brackets) internal view returns(uint16 middleRoundResults){
uint8 teamId;
for (uint i = 0; i < size; i++){
teamId = uint8(brackets & RESULT_MASK_BRACKETS);
if (uint(bracketsResults.middlePhaseTeamsIds[teamId]) >= uint(round) ) {
middleRoundResults+=60;
}
brackets = brackets >> 5;
}
}
/**
* @notice calculates points for correct predictions of group winners
* @param brackets token predictions
* @return amount of points
*/
function getQualifiersPoints(uint160 brackets) internal view returns(uint16 qualifiersPoints){
uint8 teamId;
for (uint256 i = 0; i <= 15; i++){
teamId = uint8(brackets & RESULT_MASK_BRACKETS);
if (teamId == bracketsResults.roundOfSixteenTeamsIds[15-i]){
qualifiersPoints+=30;
} else if (bracketsResults.teamExists[teamId]){
qualifiersPoints+=25;
}
brackets = brackets >> 5;
}
}
/**
* @notice calculates points won by yellow and red cards predictions
* @param extras token predictions
* @return amount of points
*/
function getExtraPoints(uint32 extras) internal view returns(uint16 extraPoints){
uint16 redCards = uint16(extras & EXTRA_MASK_BRACKETS);
extras = extras >> 16;
uint16 yellowCards = uint16(extras);
if (redCards == extraResults.redCards){
extraPoints+=20;
}
if (yellowCards == extraResults.yellowCards){
extraPoints+=20;
}
}
/**
* @notice calculates total amount of points for a token
* @param t token to calculate points for
* @return total amount of points
*/
function calculateTokenPoints (Token memory t) internal view returns(uint16 points){
//Groups phase 1
uint192 g1 = t.groups1;
for (uint256 i = 0; i <= 23; i++){
points+=getMatchPointsGroups(23-i, g1);
g1 = g1 >> 8;
}
//Groups phase 2
uint192 g2 = t.groups2;
for (i = 0; i <= 23; i++){
points+=getMatchPointsGroups(47-i, g2);
g2 = g2 >> 8;
}
uint160 bracketsLocal = t.brackets;
//Brackets phase 1
points+=getFinalRoundPoints(bracketsLocal);
bracketsLocal = bracketsLocal >> 20;
//Brackets phase 2
points+=getMiddleRoundPoints(4, teamState.QUARTERS, bracketsLocal);
bracketsLocal = bracketsLocal >> 20;
//Brackets phase 3
points+=getMiddleRoundPoints(8, teamState.ROS, bracketsLocal);
bracketsLocal = bracketsLocal >> 40;
//Brackets phase 4
points+=getQualifiersPoints(bracketsLocal);
//Extras
points+=getExtraPoints(t.extra);
}
/**
* @notice Sets the points of all the tokens between the last chunk set and the amount given.
* @dev This function uses all the data collected earlier by oraclize to calculate points.
* @param amount The amount of tokens that should be analyzed.
*/
function calculatePointsBlock(uint32 amount) external{
require (gameFinishedTime == 0);
require(amount + lastCheckedToken <= tokens.length);
for (uint256 i = lastCalculatedToken; i < (lastCalculatedToken + amount); i++) {
uint16 points = calculateTokenPoints(tokens[i]);
tokenToPointsMap[i] = points;
if(worstTokens.length == 0 || points <= auxWorstPoints){
if(worstTokens.length != 0 && points < auxWorstPoints){
worstTokens.length = 0;
}
if(worstTokens.length < 100){
auxWorstPoints = points;
worstTokens.push(i);
}
}
}
lastCalculatedToken += amount;
}
/**
* @notice Sets the structures for payout distribution, last position and superior quota. Payout distribution is the
* percentage of the pot each position gets, last position is the percentage of the pot the last position gets,
* and superior quota is the total amount OF winners that are given a prize.
* @dev Each of this structures is dynamic and is assigned depending on the total amount of tokens in the game
*/
function setPayoutDistributionId () internal {
if(tokens.length < 101){
payoutDistribution = [289700, 189700, 120000, 92500, 75000, 62500, 52500, 42500, 40000, 35600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
lastPosition = 0;
superiorQuota = 10;
}else if(tokens.length < 201){
payoutDistribution = [265500, 165500, 105500, 75500, 63000, 48000, 35500, 20500, 20000, 19500, 18500, 17800, 0, 0, 0, 0, 0, 0, 0, 0, 0];
lastPosition = 0;
superiorQuota = 20;
}else if(tokens.length < 301){
payoutDistribution = [260700, 155700, 100700, 70900, 60700, 45700, 35500, 20500, 17900, 12500, 11500, 11000, 10670, 0, 0, 0, 0, 0, 0, 0, 0];
lastPosition = 0;
superiorQuota = 30;
}else if(tokens.length < 501){
payoutDistribution = [238600, 138600, 88800, 63800, 53800, 43800, 33800, 18800, 17500, 12500, 9500, 7500, 7100, 6700, 0, 0, 0, 0, 0, 0, 0];
lastPosition = 0;
superiorQuota = 50;
}else if(tokens.length < 1001){
payoutDistribution = [218300, 122300, 72300, 52400, 43900, 33900, 23900, 16000, 13000, 10000, 9000, 7000, 5000, 4000, 3600, 0, 0, 0, 0, 0, 0];
lastPosition = 4000;
superiorQuota = 100;
}else if(tokens.length < 2001){
payoutDistribution = [204500, 114000, 64000, 44100, 35700, 26700, 22000, 15000, 11000, 9500, 8500, 6500, 4600, 2500, 2000, 1800, 0, 0, 0, 0, 0];
lastPosition = 2500;
superiorQuota = 200;
}else if(tokens.length < 3001){
payoutDistribution = [189200, 104800, 53900, 34900, 29300, 19300, 15300, 14000, 10500, 8300, 8000, 6000, 3800, 2500, 2000, 1500, 1100, 0, 0, 0, 0];
lastPosition = 2500;
superiorQuota = 300;
}else if(tokens.length < 5001){
payoutDistribution = [178000, 100500, 47400, 30400, 24700, 15500, 15000, 12000, 10200, 7800, 7400, 5500, 3300, 2000, 1500, 1200, 900, 670, 0, 0, 0];
lastPosition = 2000;
superiorQuota = 500;
}else if(tokens.length < 10001){
payoutDistribution = [157600, 86500, 39000, 23100, 18900, 15000, 14000, 11000, 9300, 6100, 6000, 5000, 3800, 1500, 1100, 900, 700, 500, 360, 0, 0];
lastPosition = 1500;
superiorQuota = 1000;
}else if(tokens.length < 25001){
payoutDistribution = [132500, 70200, 31300, 18500, 17500, 14000, 13500, 10500, 7500, 5500, 5000, 4000, 3000, 1000, 900, 700, 600, 400, 200, 152, 0];
lastPosition = 1000;
superiorQuota = 2500;
} else {
payoutDistribution = [120000, 63000, 27000, 18800, 17300, 13700, 13000, 10000, 6300, 5000, 4500, 3900, 2500, 900, 800, 600, 500, 350, 150, 100, 70];
lastPosition = 900;
superiorQuota = 5000;
}
}
/**
* @notice Sets the id of the last token that will be given a prize.
* @dev This is done to offload some of the calculations needed for sorting, and to cap the number of sorts
* needed to just the winners and not the whole array of tokens.
* @param tokenId last token id
*/
function setLimit(uint256 tokenId) external onlyAdmin{
require(tokenId < tokens.length);
require(pValidationState == pointsValidationState.Unstarted || pValidationState == pointsValidationState.LimitSet);
pointsLimit = tokenId;
pValidationState = pointsValidationState.LimitSet;
lastCheckedToken = 0;
lastCalculatedToken = 0;
winnerCounter = 0;
setPayoutDistributionId();
}
/**
* @notice Sets the 10th percentile of the sorted array of points
* @param amount tokens in a chunk
*/
function calculateWinners(uint32 amount) external onlyAdmin checkState(pointsValidationState.LimitSet){
require(amount + lastCheckedToken <= tokens.length);
uint256 points = tokenToPointsMap[pointsLimit];
for(uint256 i = lastCheckedToken; i < lastCheckedToken + amount; i++){
if(tokenToPointsMap[i] > points ||
(tokenToPointsMap[i] == points && i <= pointsLimit)){
winnerCounter++;
}
}
lastCheckedToken += amount;
if(lastCheckedToken == tokens.length){
require(superiorQuota == winnerCounter);
pValidationState = pointsValidationState.LimitCalculated;
}
}
/**
* @notice Checks if the order given offchain coincides with the order of the actual previously calculated points
* in the smart contract.
* @dev the token sorting is done offchain so as to save on the huge amount of gas and complications that
* could occur from doing all the sorting onchain.
* @param sortedChunk chunk sorted by points
*/
function checkOrder(uint32[] sortedChunk) external onlyAdmin checkState(pointsValidationState.LimitCalculated){
require(sortedChunk.length + sortedWinners.length <= winnerCounter);
for(uint256 i=0;i < sortedChunk.length-1;i++){
uint256 id = sortedChunk[i];
uint256 sigId = sortedChunk[i+1];
require(tokenToPointsMap[id] > tokenToPointsMap[sigId] ||
(tokenToPointsMap[id] == tokenToPointsMap[sigId] && id < sigId));
}
if(sortedWinners.length != 0){
uint256 id2 = sortedWinners[sortedWinners.length-1];
uint256 sigId2 = sortedChunk[0];
require(tokenToPointsMap[id2] > tokenToPointsMap[sigId2] ||
(tokenToPointsMap[id2] == tokenToPointsMap[sigId2] && id2 < sigId2));
}
for(uint256 j=0;j < sortedChunk.length;j++){
sortedWinners.push(sortedChunk[j]);
}
if(sortedWinners.length == winnerCounter){
require(sortedWinners[sortedWinners.length-1] == pointsLimit);
pValidationState = pointsValidationState.OrderChecked;
}
}
/**
* @notice If anything during the point calculation and sorting part should fail, this function can reset
* data structures to their initial position, so as to
*/
function resetWinners(uint256 newLength) external onlyAdmin checkState(pointsValidationState.LimitCalculated){
sortedWinners.length = newLength;
}
/**
* @notice Assigns prize percentage for the lucky top 30 winners. Each token will be assigned a uint256 inside
* tokenToPayoutMap structure that represents the size of the pot that belongs to that token. If any tokens
* tie inside of the first 30 tokens, the prize will be summed and divided equally.
*/
function setTopWinnerPrizes() external onlyAdmin checkState(pointsValidationState.OrderChecked){
uint256 percent = 0;
uint[] memory tokensEquals = new uint[](30);
uint16 tokenEqualsCounter = 0;
uint256 currentTokenId;
uint256 currentTokenPoints;
uint256 lastTokenPoints;
uint32 counter = 0;
uint256 maxRange = 13;
if(tokens.length < 201){
maxRange = 10;
}
while(payoutRange < maxRange){
uint256 inRangecounter = payDistributionAmount[payoutRange];
while(inRangecounter > 0){
currentTokenId = sortedWinners[counter];
currentTokenPoints = tokenToPointsMap[currentTokenId];
inRangecounter--;
//Special case for the last one
if(inRangecounter == 0 && payoutRange == maxRange - 1){
if(currentTokenPoints == lastTokenPoints){
percent += payoutDistribution[payoutRange];
tokensEquals[tokenEqualsCounter] = currentTokenId;
tokenEqualsCounter++;
}else{
tokenToPayoutMap[currentTokenId] = payoutDistribution[payoutRange];
}
}
if(counter != 0 && (currentTokenPoints != lastTokenPoints || (inRangecounter == 0 && payoutRange == maxRange - 1))){ //Fix second condition
for(uint256 i=0;i < tokenEqualsCounter;i++){
tokenToPayoutMap[tokensEquals[i]] = percent.div(tokenEqualsCounter);
}
percent = 0;
tokensEquals = new uint[](30);
tokenEqualsCounter = 0;
}
percent += payoutDistribution[payoutRange];
tokensEquals[tokenEqualsCounter] = currentTokenId;
tokenEqualsCounter++;
counter++;
lastTokenPoints = currentTokenPoints;
}
payoutRange++;
}
pValidationState = pointsValidationState.TopWinnersAssigned;
lastPrizeGiven = counter;
}
/**
* @notice Sets prize percentage to every address that wins from the position 30th onwards
* @dev If there are less than 300 tokens playing, then this function will set nothing.
* @param amount tokens in a chunk
*/
function setWinnerPrizes(uint32 amount) external onlyAdmin checkState(pointsValidationState.TopWinnersAssigned){
require(lastPrizeGiven + amount <= winnerCounter);
uint16 inRangeCounter = payDistributionAmount[payoutRange];
for(uint256 i = 0; i < amount; i++){
if (inRangeCounter == 0){
payoutRange++;
inRangeCounter = payDistributionAmount[payoutRange];
}
uint256 tokenId = sortedWinners[i + lastPrizeGiven];
tokenToPayoutMap[tokenId] = payoutDistribution[payoutRange];
inRangeCounter--;
}
//i + amount prize was not given yet, so amount -1
lastPrizeGiven += amount;
payDistributionAmount[payoutRange] = inRangeCounter;
if(lastPrizeGiven == winnerCounter){
pValidationState = pointsValidationState.WinnersAssigned;
return;
}
}
/**
* @notice Sets prizes for last tokens and sets prize pool amount
*/
function setLastPositions() external onlyAdmin checkState(pointsValidationState.WinnersAssigned){
for(uint256 j = 0;j < worstTokens.length;j++){
uint256 tokenId = worstTokens[j];
tokenToPayoutMap[tokenId] += lastPosition.div(worstTokens.length);
}
uint256 balance = address(this).balance;
adminPool = balance.mul(25).div(100);
prizePool = balance.mul(75).div(100);
pValidationState = pointsValidationState.Finished;
gameFinishedTime = now;
}
}
/**
* @title CoreLayer
* @author CryptoCup Team (https://cryptocup.io/about)
* @notice Main contract
*/
contract CoreLayer is GameLogicLayer {
function CoreLayer() public {
adminAddress = msg.sender;
deploymentTime = now;
}
/**
* @dev Only accept eth from the admin
*/
function() external payable {
require(msg.sender == adminAddress);
}
function isDataSourceCallback() public pure returns (bool){
return true;
}
/**
* @notice Builds ERC721 token with the predictions provided by the user.
* @param groups1 - First half of the group matches scores encoded in a uint192.
* @param groups2 - Second half of the groups matches scores encoded in a uint192.
* @param brackets - Bracket information encoded in a uint160.
* @param extra - Extra information (number of red cards and yellow cards) encoded in a uint32.
* @dev An automatic timestamp is added for internal use.
*/
function buildToken(uint192 groups1, uint192 groups2, uint160 brackets, uint32 extra) external payable isNotPaused {
Token memory token = Token({
groups1: groups1,
groups2: groups2,
brackets: brackets,
timeStamp: uint64(now),
extra: extra
});
require(msg.value >= _getTokenPrice());
require(msg.sender != address(0));
require(tokens.length < WCCTOKEN_CREATION_LIMIT);
require(tokensOfOwnerMap[msg.sender].length < 100);
require(now < WORLD_CUP_START); //World cup Start
uint256 tokenId = tokens.push(token) - 1;
require(tokenId == uint256(uint32(tokenId)));
_setTokenOwner(msg.sender, tokenId);
LogTokenBuilt(msg.sender, tokenId, token);
}
/**
* @param tokenId - ID of token to get.
* @return Returns all the valuable information about a specific token.
*/
function getToken(uint256 tokenId) external view returns (uint192 groups1, uint192 groups2, uint160 brackets, uint64 timeStamp, uint32 extra) {
Token storage token = tokens[tokenId];
groups1 = token.groups1;
groups2 = token.groups2;
brackets = token.brackets;
timeStamp = token.timeStamp;
extra = token.extra;
}
/**
* @notice Called by the development team once the World Cup has ended (adminPool is set)
* @dev Allows dev team to retrieve adminPool
*/
function adminWithdrawBalance() external onlyAdmin {
adminAddress.transfer(adminPool);
adminPool = 0;
}
/**
* @notice Allows any user to retrieve their asigned prize. This would be the sum of the price of all the tokens
* owned by the caller of this function.
* @dev If the caller has no prize, the function will revert costing no gas to the caller.
*/
function withdrawPrize() external checkState(pointsValidationState.Finished){
uint256 prize = 0;
uint256[] memory tokenList = tokensOfOwnerMap[msg.sender];
for(uint256 i = 0;i < tokenList.length; i++){
prize += tokenToPayoutMap[tokenList[i]];
tokenToPayoutMap[tokenList[i]] = 0;
}
require(prize > 0);
msg.sender.transfer((prizePool.mul(prize)).div(1000000));
}
/**
* @notice Gets current token price
*/
function _getTokenPrice() internal view returns(uint256 tokenPrice){
if ( now >= THIRD_PHASE){
tokenPrice = (150 finney);
} else if (now >= SECOND_PHASE) {
tokenPrice = (110 finney);
} else if (now >= FIRST_PHASE) {
tokenPrice = (75 finney);
} else {
tokenPrice = STARTING_PRICE;
}
require(tokenPrice >= STARTING_PRICE && tokenPrice <= (200 finney));
}
/**
* @dev Sets the data source contract address
* @param _address Address to be set
*/
function setDataSourceAddress(address _address) external onlyAdmin {
DataSourceInterface c = DataSourceInterface(_address);
require(c.isDataSource());
dataSource = c;
dataSourceAddress = _address;
}
/**
* @notice Testing function to corroborate group data from oraclize call
* @param x Id of the match to get
* @return uint8 Team 1 goals
* @return uint8 Team 2 goals
*/
function getGroupData(uint x) external view returns(uint8 a, uint8 b){
a = groupsResults[x].teamOneGoals;
b = groupsResults[x].teamTwoGoals;
}
/**
* @notice Testing function to corroborate round of sixteen data from oraclize call
* @return An array with the ids of the round of sixteen teams
*/
function getBracketData() external view returns(uint8[16] a){
a = bracketsResults.roundOfSixteenTeamsIds;
}
/**
* @notice Testing function to corroborate brackets data from oraclize call
* @param x Team id
* @return The place the team reached
*/
function getBracketDataMiddleTeamIds(uint8 x) external view returns(teamState a){
a = bracketsResults.middlePhaseTeamsIds[x];
}
/**
* @notice Testing function to corroborate finals data from oraclize call
* @return the 4 (four) final teams ids
*/
function getBracketDataFinals() external view returns(uint8[4] a){
a = bracketsResults.finalsTeamsIds;
}
/**
* @notice Testing function to corroborate extra data from oraclize call
* @return amount of yellow and red cards
*/
function getExtrasData() external view returns(uint16 a, uint16 b){
a = extraResults.yellowCards;
b = extraResults.redCards;
}
//EMERGENCY CALLS
//If something goes wrong or fails, these functions will allow retribution for token holders
/**
* @notice if there is an unresolvable problem, users can call to this function to get a refund.
*/
function emergencyWithdraw() external hasFinalized{
uint256 balance = STARTING_PRICE * tokensOfOwnerMap[msg.sender].length;
delete tokensOfOwnerMap[msg.sender];
msg.sender.transfer(balance);
}
/**
* @notice Let the admin cash-out the entire contract balance 10 days after game has finished.
*/
function finishedGameWithdraw() external onlyAdmin hasFinished{
uint256 balance = address(this).balance;
adminAddress.transfer(balance);
}
/**
* @notice Let the admin cash-out the entire contract balance 10 days after game has finished.
*/
function emergencyWithdrawAdmin() external hasFinalized onlyAdmin{
require(finalizedTime != 0 && now >= finalizedTime + 10 days );
msg.sender.transfer(address(this).balance);
}
} | set this to now when oraclize was called.
| uint256 public gameFinishedTime = 0; | 7,712,429 | [
1,
542,
333,
358,
2037,
1347,
578,
10150,
554,
1703,
2566,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
7920,
10577,
950,
273,
374,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/3/0xa098aD72547e2F944aFEF56572aeBa1318b37E32/sources/ethmax.sol | get ETHmax Boost Rate +1.05% for every 100 more ETH (Maximum Boost Rate is 2815.575%) | function getBoostRate() public view returns (uint256) {
uint256 contractBalance = address(this).balance;
return min(contractBalance.div(CONTRACT_BALANCE_STEP).mul(2), 4856);
}
| 5,089,723 | [
1,
588,
512,
2455,
1896,
17980,
669,
13025,
397,
21,
18,
6260,
9,
364,
3614,
2130,
1898,
512,
2455,
261,
13528,
17980,
669,
13025,
353,
9131,
3600,
18,
25,
5877,
9,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
2882,
83,
669,
4727,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
202,
202,
11890,
5034,
6835,
13937,
273,
1758,
12,
2211,
2934,
12296,
31,
203,
202,
202,
2463,
1131,
12,
16351,
13937,
18,
2892,
12,
6067,
2849,
1268,
67,
38,
1013,
4722,
67,
26951,
2934,
16411,
12,
22,
3631,
9934,
4313,
1769,
203,
202,
97,
203,
202,
203,
202,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// Contract based on https://docs.openzeppelin.com/contracts/3.x/erc721
pragma solidity ^0.7.3;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract SaturnaNFT is ERC721, Ownable {
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter public _tokenIds;
Counters.Counter public _NFTTypeIds;
IERC20 public saturna;
// Mapping NFT Type ID to its URI and count
mapping (uint256 => NFT) public NFTTypeMap;
mapping (address => mapping (uint256 => uint256[])) public NFTAddressToID;
mapping (address => bool) public isWhitelisted;
address public devAddress;
constructor(address _saturnaAddress, address _devAddress)
public ERC721("SATURNA", "SAT") {
isWhitelisted[msg.sender] = true;
saturna = IERC20(_saturnaAddress);
devAddress = _devAddress;
}
struct NFT {
uint256 typeId;
uint256 count;
uint256 minted;
string tokenURI;
uint256 price;
uint256 startTimestamp;
uint256 endTimestamp;
uint256 saturnaAmount;
}
modifier onlyWhitelist() {
require(isWhitelisted[_msgSender()], "Whitelist: Address not whitelisted");
_;
}
receive() external payable {}
function addWhitelist(address _whitelistAddress) external onlyOwner {
isWhitelisted[_whitelistAddress] = true;
}
function removeWhitelist(address _whitelistAddress) external onlyOwner {
require(isWhitelisted[_whitelistAddress], "User does not exist");
isWhitelisted[_whitelistAddress] = false;
}
function addNFT(uint256 _count, string memory _tokenURI, uint256 _price,
uint256 _startTimestamp, uint256 _endTimestamp, uint256 _saturnaAmount)
external onlyWhitelist returns (uint256) {
uint256 typeId = _NFTTypeIds.current();
NFTTypeMap[typeId] = NFT(typeId, _count, 0, _tokenURI, _price,
_startTimestamp, _endTimestamp, _saturnaAmount);
_NFTTypeIds.increment();
return typeId;
}
function buyNFT(uint256 typeId) external payable returns (uint256) {
_tokenIds.increment();
address recipient = msg.sender;
NFT memory nft = NFTTypeMap[typeId];
// Make sure buyer is paying right price
require(msg.value == nft.price, "Price is incorrect");
// Make sure there are NFTs still available
require(nft.count > 0, "NFTs are not available");
require(nft.startTimestamp <= block.timestamp, "Too early to get NFT");
require(nft.endTimestamp >= block.timestamp, "Too late to get NFT");
// Make sure buyer holds correct amount of saturna
require(saturna.balanceOf(msg.sender) >= nft.saturnaAmount,
"Need to hold correct amount of saturna in wallet");
// Remove NFT from minting
uint256 count = NFTTypeMap[typeId].count;
uint256 minted = NFTTypeMap[typeId].minted;
NFTTypeMap[typeId].count = count.sub(1);
NFTTypeMap[typeId].minted = minted.add(1);
uint256 newItemId = _tokenIds.current();
NFTAddressToID[recipient][typeId].push(newItemId);
// Changed this to be safeMint from Mint
_safeMint(recipient, newItemId);
_setTokenURI(newItemId, nft.tokenURI);
uint256 devAmount = (msg.value).mul(10).div(100);
payable(devAddress).transfer(devAmount);
return newItemId;
}
function setSaturnaAddress (address _saturnaAddress) external onlyOwner {
saturna = IERC20(_saturnaAddress);
}
function setNFTMint (uint256 typeId, uint256 _minted) external onlyWhitelist {
NFTTypeMap[typeId].minted = _minted;
}
function setNFTCount (uint256 typeId, uint256 _count) external onlyWhitelist {
NFTTypeMap[typeId].count = _count;
}
function setNFTSaturnaAmount (uint256 typeId, uint256 _saturnaAmount)
external onlyWhitelist {
NFTTypeMap[typeId].saturnaAmount = _saturnaAmount;
}
function setNFTStartTimestamp (uint256 typeId, uint256 _startTimestamp)
external onlyWhitelist {
NFTTypeMap[typeId].startTimestamp = _startTimestamp;
}
function setNFTEndTimestamp (uint256 typeId, uint256 _endTimestamp)
external onlyWhitelist {
NFTTypeMap[typeId].endTimestamp = _endTimestamp;
}
function setNFTTokenURI (uint256 typeId, string memory _tokenURI)
external onlyWhitelist {
NFTTypeMap[typeId].tokenURI = _tokenURI;
}
function setNFTPrice (uint256 typeId, uint256 _price) external onlyWhitelist {
NFTTypeMap[typeId].price = _price;
}
function getNFTCount (uint256 typeId) external view returns (uint256) {
return NFTTypeMap[typeId].count;
}
function getNFTPrice (uint256 typeId) external view returns (uint256) {
return NFTTypeMap[typeId].price;
}
function getNFTMint (uint256 typeId) external view returns (uint256) {
return NFTTypeMap[typeId].minted;
}
function getNFTTokenURI (uint256 typeId) external view returns
(string memory) {
return NFTTypeMap[typeId].tokenURI;
}
function isNFTAvailable (uint256 typeId) external view returns (bool) {
return NFTTypeMap[typeId].count > 0;
}
function getIDFromMap (address wallet, uint256 packId) external view returns (uint256[] memory) {
return NFTAddressToID[wallet][packId];
}
function withdrawFunds(address _payeeWallet) external onlyOwner returns (bool) {
require(address(this).balance > 0);
payable(_payeeWallet).transfer(address(this).balance);
return true;
}
function setDevAddress (address _devAddress) external onlyOwner {
devAddress = _devAddress;
}
}
| Mapping NFT Type ID to its URI and count | contract SaturnaNFT is ERC721, Ownable {
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter public _tokenIds;
Counters.Counter public _NFTTypeIds;
IERC20 public saturna;
mapping (uint256 => NFT) public NFTTypeMap;
mapping (address => mapping (uint256 => uint256[])) public NFTAddressToID;
mapping (address => bool) public isWhitelisted;
address public devAddress;
constructor(address _saturnaAddress, address _devAddress)
public ERC721("SATURNA", "SAT") {
isWhitelisted[msg.sender] = true;
saturna = IERC20(_saturnaAddress);
devAddress = _devAddress;
}
struct NFT {
uint256 typeId;
uint256 count;
uint256 minted;
string tokenURI;
uint256 price;
uint256 startTimestamp;
uint256 endTimestamp;
uint256 saturnaAmount;
}
modifier onlyWhitelist() {
require(isWhitelisted[_msgSender()], "Whitelist: Address not whitelisted");
_;
}
receive() external payable {}
function addWhitelist(address _whitelistAddress) external onlyOwner {
isWhitelisted[_whitelistAddress] = true;
}
function removeWhitelist(address _whitelistAddress) external onlyOwner {
require(isWhitelisted[_whitelistAddress], "User does not exist");
isWhitelisted[_whitelistAddress] = false;
}
function addNFT(uint256 _count, string memory _tokenURI, uint256 _price,
uint256 _startTimestamp, uint256 _endTimestamp, uint256 _saturnaAmount)
external onlyWhitelist returns (uint256) {
uint256 typeId = _NFTTypeIds.current();
NFTTypeMap[typeId] = NFT(typeId, _count, 0, _tokenURI, _price,
_startTimestamp, _endTimestamp, _saturnaAmount);
_NFTTypeIds.increment();
return typeId;
}
function buyNFT(uint256 typeId) external payable returns (uint256) {
_tokenIds.increment();
address recipient = msg.sender;
NFT memory nft = NFTTypeMap[typeId];
require(msg.value == nft.price, "Price is incorrect");
require(nft.count > 0, "NFTs are not available");
require(nft.startTimestamp <= block.timestamp, "Too early to get NFT");
require(nft.endTimestamp >= block.timestamp, "Too late to get NFT");
require(saturna.balanceOf(msg.sender) >= nft.saturnaAmount,
"Need to hold correct amount of saturna in wallet");
uint256 count = NFTTypeMap[typeId].count;
uint256 minted = NFTTypeMap[typeId].minted;
NFTTypeMap[typeId].count = count.sub(1);
NFTTypeMap[typeId].minted = minted.add(1);
uint256 newItemId = _tokenIds.current();
NFTAddressToID[recipient][typeId].push(newItemId);
_safeMint(recipient, newItemId);
_setTokenURI(newItemId, nft.tokenURI);
uint256 devAmount = (msg.value).mul(10).div(100);
payable(devAddress).transfer(devAmount);
return newItemId;
}
function setSaturnaAddress (address _saturnaAddress) external onlyOwner {
saturna = IERC20(_saturnaAddress);
}
function setNFTMint (uint256 typeId, uint256 _minted) external onlyWhitelist {
NFTTypeMap[typeId].minted = _minted;
}
function setNFTCount (uint256 typeId, uint256 _count) external onlyWhitelist {
NFTTypeMap[typeId].count = _count;
}
function setNFTSaturnaAmount (uint256 typeId, uint256 _saturnaAmount)
external onlyWhitelist {
NFTTypeMap[typeId].saturnaAmount = _saturnaAmount;
}
function setNFTStartTimestamp (uint256 typeId, uint256 _startTimestamp)
external onlyWhitelist {
NFTTypeMap[typeId].startTimestamp = _startTimestamp;
}
function setNFTEndTimestamp (uint256 typeId, uint256 _endTimestamp)
external onlyWhitelist {
NFTTypeMap[typeId].endTimestamp = _endTimestamp;
}
function setNFTTokenURI (uint256 typeId, string memory _tokenURI)
external onlyWhitelist {
NFTTypeMap[typeId].tokenURI = _tokenURI;
}
function setNFTPrice (uint256 typeId, uint256 _price) external onlyWhitelist {
NFTTypeMap[typeId].price = _price;
}
function getNFTCount (uint256 typeId) external view returns (uint256) {
return NFTTypeMap[typeId].count;
}
function getNFTPrice (uint256 typeId) external view returns (uint256) {
return NFTTypeMap[typeId].price;
}
function getNFTMint (uint256 typeId) external view returns (uint256) {
return NFTTypeMap[typeId].minted;
}
function getNFTTokenURI (uint256 typeId) external view returns
(string memory) {
return NFTTypeMap[typeId].tokenURI;
}
function isNFTAvailable (uint256 typeId) external view returns (bool) {
return NFTTypeMap[typeId].count > 0;
}
function getIDFromMap (address wallet, uint256 packId) external view returns (uint256[] memory) {
return NFTAddressToID[wallet][packId];
}
function withdrawFunds(address _payeeWallet) external onlyOwner returns (bool) {
require(address(this).balance > 0);
payable(_payeeWallet).transfer(address(this).balance);
return true;
}
function setDevAddress (address _devAddress) external onlyOwner {
devAddress = _devAddress;
}
}
| 14,068,970 | [
1,
3233,
423,
4464,
1412,
1599,
358,
2097,
3699,
471,
1056,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
25793,
321,
6491,
4464,
353,
4232,
39,
27,
5340,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
565,
9354,
87,
18,
4789,
1071,
389,
2316,
2673,
31,
203,
565,
9354,
87,
18,
4789,
1071,
389,
50,
4464,
559,
2673,
31,
203,
377,
203,
565,
467,
654,
39,
3462,
1071,
5942,
321,
69,
31,
203,
565,
2874,
261,
11890,
5034,
516,
423,
4464,
13,
1071,
423,
4464,
23968,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
11890,
5034,
516,
2254,
5034,
8526,
3719,
1071,
423,
4464,
1887,
774,
734,
31,
203,
203,
565,
2874,
261,
2867,
516,
1426,
13,
1071,
353,
18927,
329,
31,
203,
203,
565,
1758,
1071,
4461,
1887,
31,
203,
203,
565,
3885,
12,
2867,
389,
12973,
321,
69,
1887,
16,
1758,
389,
5206,
1887,
13,
7010,
377,
203,
203,
203,
565,
1071,
4232,
39,
27,
5340,
2932,
55,
789,
8521,
37,
3113,
315,
55,
789,
7923,
288,
203,
3639,
353,
18927,
329,
63,
3576,
18,
15330,
65,
273,
638,
31,
203,
3639,
5942,
321,
69,
273,
467,
654,
39,
3462,
24899,
12973,
321,
69,
1887,
1769,
203,
3639,
4461,
1887,
273,
389,
5206,
1887,
31,
203,
565,
289,
203,
203,
565,
1958,
423,
4464,
288,
203,
3639,
2254,
5034,
24361,
31,
203,
3639,
2254,
5034,
1056,
31,
203,
3639,
2254,
5034,
312,
474,
329,
31,
203,
3639,
533,
1147,
3098,
31,
203,
3639,
2254,
5034,
6205,
31,
203,
3639,
2254,
5034,
787,
2
] |
pragma solidity ^0.4.23;
// File: contracts/TokenSale.sol
contract TokenSale {
/**
* Buy tokens for the beneficiary using paid Ether.
* @param beneficiary the beneficiary address that will receive the tokens.
*/
function buyTokens(address beneficiary) public payable;
}
// File: contracts/WhitelistableConstraints.sol
/**
* @title WhitelistableConstraints
* @dev Contract encapsulating the constraints applicable to a Whitelistable contract.
*/
contract WhitelistableConstraints {
/**
* @dev Check if whitelist with specified parameters is allowed.
* @param _maxWhitelistLength The maximum length of whitelist. Zero means no whitelist.
* @param _weiWhitelistThresholdBalance The threshold balance triggering whitelist check.
* @return true if whitelist with specified parameters is allowed, false otherwise
*/
function isAllowedWhitelist(uint256 _maxWhitelistLength, uint256 _weiWhitelistThresholdBalance)
public pure returns(bool isReallyAllowedWhitelist) {
return _maxWhitelistLength > 0 || _weiWhitelistThresholdBalance > 0;
}
}
// File: contracts/Whitelistable.sol
/**
* @title Whitelistable
* @dev Base contract implementing a whitelist to keep track of investors.
* The construction parameters allow for both whitelisted and non-whitelisted contracts:
* 1) maxWhitelistLength = 0 and whitelistThresholdBalance > 0: whitelist disabled
* 2) maxWhitelistLength > 0 and whitelistThresholdBalance = 0: whitelist enabled, full whitelisting
* 3) maxWhitelistLength > 0 and whitelistThresholdBalance > 0: whitelist enabled, partial whitelisting
*/
contract Whitelistable is WhitelistableConstraints {
event LogMaxWhitelistLengthChanged(address indexed caller, uint256 indexed maxWhitelistLength);
event LogWhitelistThresholdBalanceChanged(address indexed caller, uint256 indexed whitelistThresholdBalance);
event LogWhitelistAddressAdded(address indexed caller, address indexed subscriber);
event LogWhitelistAddressRemoved(address indexed caller, address indexed subscriber);
mapping (address => bool) public whitelist;
uint256 public whitelistLength;
uint256 public maxWhitelistLength;
uint256 public whitelistThresholdBalance;
constructor(uint256 _maxWhitelistLength, uint256 _whitelistThresholdBalance) internal {
require(isAllowedWhitelist(_maxWhitelistLength, _whitelistThresholdBalance), "parameters not allowed");
maxWhitelistLength = _maxWhitelistLength;
whitelistThresholdBalance = _whitelistThresholdBalance;
}
/**
* @return true if whitelist is currently enabled, false otherwise
*/
function isWhitelistEnabled() public view returns(bool isReallyWhitelistEnabled) {
return maxWhitelistLength > 0;
}
/**
* @return true if subscriber is whitelisted, false otherwise
*/
function isWhitelisted(address _subscriber) public view returns(bool isReallyWhitelisted) {
return whitelist[_subscriber];
}
function setMaxWhitelistLengthInternal(uint256 _maxWhitelistLength) internal {
require(isAllowedWhitelist(_maxWhitelistLength, whitelistThresholdBalance),
"_maxWhitelistLength not allowed");
require(_maxWhitelistLength != maxWhitelistLength, "_maxWhitelistLength equal to current one");
maxWhitelistLength = _maxWhitelistLength;
emit LogMaxWhitelistLengthChanged(msg.sender, maxWhitelistLength);
}
function setWhitelistThresholdBalanceInternal(uint256 _whitelistThresholdBalance) internal {
require(isAllowedWhitelist(maxWhitelistLength, _whitelistThresholdBalance),
"_whitelistThresholdBalance not allowed");
require(whitelistLength == 0 || _whitelistThresholdBalance > whitelistThresholdBalance,
"_whitelistThresholdBalance not greater than current one");
whitelistThresholdBalance = _whitelistThresholdBalance;
emit LogWhitelistThresholdBalanceChanged(msg.sender, _whitelistThresholdBalance);
}
function addToWhitelistInternal(address _subscriber) internal {
require(_subscriber != address(0), "_subscriber is zero");
require(!whitelist[_subscriber], "already whitelisted");
require(whitelistLength < maxWhitelistLength, "max whitelist length reached");
whitelistLength++;
whitelist[_subscriber] = true;
emit LogWhitelistAddressAdded(msg.sender, _subscriber);
}
function removeFromWhitelistInternal(address _subscriber, uint256 _balance) internal {
require(_subscriber != address(0), "_subscriber is zero");
require(whitelist[_subscriber], "not whitelisted");
require(_balance <= whitelistThresholdBalance, "_balance greater than whitelist threshold");
assert(whitelistLength > 0);
whitelistLength--;
whitelist[_subscriber] = false;
emit LogWhitelistAddressRemoved(msg.sender, _subscriber);
}
/**
* @param _subscriber The subscriber for which the balance check is required.
* @param _balance The balance value to check for allowance.
* @return true if the balance is allowed for the subscriber, false otherwise
*/
function isAllowedBalance(address _subscriber, uint256 _balance) public view returns(bool isReallyAllowed) {
return !isWhitelistEnabled() || _balance <= whitelistThresholdBalance || whitelist[_subscriber];
}
}
// File: openzeppelin-solidity/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.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address 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;
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol
/**
* @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;
}
}
// File: contracts/Crowdsale.sol
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end block, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale is TokenSale, Pausable, Whitelistable {
using AddressUtils for address;
using SafeMath for uint256;
event LogStartBlockChanged(uint256 indexed startBlock);
event LogEndBlockChanged(uint256 indexed endBlock);
event LogMinDepositChanged(uint256 indexed minDeposit);
event LogTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 indexed amount, uint256 tokenAmount);
// The token being sold
MintableToken public token;
// The start and end block where investments are allowed (both inclusive)
uint256 public startBlock;
uint256 public endBlock;
// How many token units a buyer gets per wei
uint256 public rate;
// Amount of raised money in wei
uint256 public raisedFunds;
// Amount of tokens already sold
uint256 public soldTokens;
// Balances in wei deposited by each subscriber
mapping (address => uint256) public balanceOf;
// The minimum balance for each subscriber in wei
uint256 public minDeposit;
modifier beforeStart() {
require(block.number < startBlock, "already started");
_;
}
modifier beforeEnd() {
require(block.number <= endBlock, "already ended");
_;
}
constructor(
uint256 _startBlock,
uint256 _endBlock,
uint256 _rate,
uint256 _minDeposit,
uint256 maxWhitelistLength,
uint256 whitelistThreshold
)
Whitelistable(maxWhitelistLength, whitelistThreshold) internal
{
require(_startBlock >= block.number, "_startBlock is lower than current block.number");
require(_endBlock >= _startBlock, "_endBlock is lower than _startBlock");
require(_rate > 0, "_rate is zero");
require(_minDeposit > 0, "_minDeposit is zero");
startBlock = _startBlock;
endBlock = _endBlock;
rate = _rate;
minDeposit = _minDeposit;
}
/*
* @return true if crowdsale event has started
*/
function hasStarted() public view returns (bool started) {
return block.number >= startBlock;
}
/*
* @return true if crowdsale event has ended
*/
function hasEnded() public view returns (bool ended) {
return block.number > endBlock;
}
/**
* Change the crowdsale start block number.
* @param _startBlock The new start block
*/
function setStartBlock(uint256 _startBlock) external onlyOwner beforeStart {
require(_startBlock >= block.number, "_startBlock < current block");
require(_startBlock <= endBlock, "_startBlock > endBlock");
require(_startBlock != startBlock, "_startBlock == startBlock");
startBlock = _startBlock;
emit LogStartBlockChanged(_startBlock);
}
/**
* Change the crowdsale end block number.
* @param _endBlock The new end block
*/
function setEndBlock(uint256 _endBlock) external onlyOwner beforeEnd {
require(_endBlock >= block.number, "_endBlock < current block");
require(_endBlock >= startBlock, "_endBlock < startBlock");
require(_endBlock != endBlock, "_endBlock == endBlock");
endBlock = _endBlock;
emit LogEndBlockChanged(_endBlock);
}
/**
* Change the minimum deposit for each subscriber. New value shall be lower than previous.
* @param _minDeposit The minimum deposit for each subscriber, expressed in wei
*/
function setMinDeposit(uint256 _minDeposit) external onlyOwner beforeEnd {
require(0 < _minDeposit && _minDeposit < minDeposit, "_minDeposit is not in [0, minDeposit]");
minDeposit = _minDeposit;
emit LogMinDepositChanged(minDeposit);
}
/**
* Change the maximum whitelist length. New value shall satisfy the #isAllowedWhitelist conditions.
* @param maxWhitelistLength The maximum whitelist length
*/
function setMaxWhitelistLength(uint256 maxWhitelistLength) external onlyOwner beforeEnd {
setMaxWhitelistLengthInternal(maxWhitelistLength);
}
/**
* Change the whitelist threshold balance. New value shall satisfy the #isAllowedWhitelist conditions.
* @param whitelistThreshold The threshold balance (in wei) above which whitelisting is required to invest
*/
function setWhitelistThresholdBalance(uint256 whitelistThreshold) external onlyOwner beforeEnd {
setWhitelistThresholdBalanceInternal(whitelistThreshold);
}
/**
* Add the subscriber to the whitelist.
* @param subscriber The subscriber to add to the whitelist.
*/
function addToWhitelist(address subscriber) external onlyOwner beforeEnd {
addToWhitelistInternal(subscriber);
}
/**
* Removed the subscriber from the whitelist.
* @param subscriber The subscriber to remove from the whitelist.
*/
function removeFromWhitelist(address subscriber) external onlyOwner beforeEnd {
removeFromWhitelistInternal(subscriber, balanceOf[subscriber]);
}
// fallback function can be used to buy tokens
function () external payable whenNotPaused {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable whenNotPaused {
require(beneficiary != address(0), "beneficiary is zero");
require(isValidPurchase(beneficiary), "invalid purchase by beneficiary");
balanceOf[beneficiary] = balanceOf[beneficiary].add(msg.value);
raisedFunds = raisedFunds.add(msg.value);
uint256 tokenAmount = calculateTokens(msg.value);
soldTokens = soldTokens.add(tokenAmount);
distributeTokens(beneficiary, tokenAmount);
emit LogTokenPurchase(msg.sender, beneficiary, msg.value, tokenAmount);
forwardFunds(msg.value);
}
/**
* @dev Overrides Whitelistable#isAllowedBalance to add minimum deposit logic.
*/
function isAllowedBalance(address beneficiary, uint256 balance) public view returns (bool isReallyAllowed) {
bool hasMinimumBalance = balance >= minDeposit;
return hasMinimumBalance && super.isAllowedBalance(beneficiary, balance);
}
/**
* @dev Determine if the token purchase is valid or not.
* @return true if the transaction can buy tokens
*/
function isValidPurchase(address beneficiary) internal view returns (bool isValid) {
bool withinPeriod = startBlock <= block.number && block.number <= endBlock;
bool nonZeroPurchase = msg.value != 0;
bool isValidBalance = isAllowedBalance(beneficiary, balanceOf[beneficiary].add(msg.value));
return withinPeriod && nonZeroPurchase && isValidBalance;
}
// Calculate the token amount given the invested ether amount.
// Override to create custom fund forwarding mechanisms
function calculateTokens(uint256 amount) internal view returns (uint256 tokenAmount) {
return amount.mul(rate);
}
/**
* @dev Distribute the token amount to the beneficiary.
* @notice Override to create custom distribution mechanisms
*/
function distributeTokens(address beneficiary, uint256 tokenAmount) internal {
token.mint(beneficiary, tokenAmount);
}
// Send ether amount to the fund collection wallet.
// override to create custom fund forwarding mechanisms
function forwardFunds(uint256 amount) internal;
}
// File: contracts/NokuPricingPlan.sol
/**
* @dev The NokuPricingPlan contract defines the responsibilities of a Noku pricing plan.
*/
contract NokuPricingPlan {
/**
* @dev Pay the fee for the service identified by the specified name.
* The fee amount shall already be approved by the client.
* @param serviceName The name of the target service.
* @param multiplier The multiplier of the base service fee to apply.
* @param client The client of the target service.
* @return true if fee has been paid.
*/
function payFee(bytes32 serviceName, uint256 multiplier, address client) public returns(bool paid);
/**
* @dev Get the usage fee for the service identified by the specified name.
* The returned fee amount shall be approved before using #payFee method.
* @param serviceName The name of the target service.
* @param multiplier The multiplier of the base service fee to apply.
* @return The amount to approve before really paying such fee.
*/
function usageFee(bytes32 serviceName, uint256 multiplier) public view returns(uint fee);
}
// File: contracts/NokuCustomToken.sol
contract NokuCustomToken is Ownable {
event LogBurnFinished();
event LogPricingPlanChanged(address indexed caller, address indexed pricingPlan);
// The pricing plan determining the fee to be paid in NOKU tokens by customers for using Noku services
NokuPricingPlan public pricingPlan;
// The entity acting as Custom Token service provider i.e. Noku
address public serviceProvider;
// Flag indicating if Custom Token burning has been permanently finished or not.
bool public burningFinished;
/**
* @dev Modifier to make a function callable only by service provider i.e. Noku.
*/
modifier onlyServiceProvider() {
require(msg.sender == serviceProvider, "caller is not service provider");
_;
}
modifier canBurn() {
require(!burningFinished, "burning finished");
_;
}
constructor(address _pricingPlan, address _serviceProvider) internal {
require(_pricingPlan != 0, "_pricingPlan is zero");
require(_serviceProvider != 0, "_serviceProvider is zero");
pricingPlan = NokuPricingPlan(_pricingPlan);
serviceProvider = _serviceProvider;
}
/**
* @dev Presence of this function indicates the contract is a Custom Token.
*/
function isCustomToken() public pure returns(bool isCustom) {
return true;
}
/**
* @dev Stop burning new tokens.
* @return true if the operation was successful.
*/
function finishBurning() public onlyOwner canBurn returns(bool finished) {
burningFinished = true;
emit LogBurnFinished();
return true;
}
/**
* @dev Change the pricing plan of service fee to be paid in NOKU tokens.
* @param _pricingPlan The pricing plan of NOKU token to be paid, zero means flat subscription.
*/
function setPricingPlan(address _pricingPlan) public onlyServiceProvider {
require(_pricingPlan != 0, "_pricingPlan is 0");
require(_pricingPlan != address(pricingPlan), "_pricingPlan == pricingPlan");
pricingPlan = NokuPricingPlan(_pricingPlan);
emit LogPricingPlanChanged(msg.sender, _pricingPlan);
}
}
// File: contracts/NokuTokenBurner.sol
contract BurnableERC20 is ERC20 {
function burn(uint256 amount) public returns (bool burned);
}
/**
* @dev The NokuTokenBurner contract has the responsibility to burn the configured fraction of received
* ERC20-compliant tokens and distribute the remainder to the configured wallet.
*/
contract NokuTokenBurner is Pausable {
using SafeMath for uint256;
event LogNokuTokenBurnerCreated(address indexed caller, address indexed wallet);
event LogBurningPercentageChanged(address indexed caller, uint256 indexed burningPercentage);
// The wallet receiving the unburnt tokens.
address public wallet;
// The percentage of tokens to burn after being received (range [0, 100])
uint256 public burningPercentage;
// The cumulative amount of burnt tokens.
uint256 public burnedTokens;
// The cumulative amount of tokens transferred back to the wallet.
uint256 public transferredTokens;
/**
* @dev Create a new NokuTokenBurner with predefined burning fraction.
* @param _wallet The wallet receiving the unburnt tokens.
*/
constructor(address _wallet) public {
require(_wallet != address(0), "_wallet is zero");
wallet = _wallet;
burningPercentage = 100;
emit LogNokuTokenBurnerCreated(msg.sender, _wallet);
}
/**
* @dev Change the percentage of tokens to burn after being received.
* @param _burningPercentage The percentage of tokens to be burnt.
*/
function setBurningPercentage(uint256 _burningPercentage) public onlyOwner {
require(0 <= _burningPercentage && _burningPercentage <= 100, "_burningPercentage not in [0, 100]");
require(_burningPercentage != burningPercentage, "_burningPercentage equal to current one");
burningPercentage = _burningPercentage;
emit LogBurningPercentageChanged(msg.sender, _burningPercentage);
}
/**
* @dev Called after burnable tokens has been transferred for burning.
* @param _token THe extended ERC20 interface supported by the sent tokens.
* @param _amount The amount of burnable tokens just arrived ready for burning.
*/
function tokenReceived(address _token, uint256 _amount) public whenNotPaused {
require(_token != address(0), "_token is zero");
require(_amount > 0, "_amount is zero");
uint256 amountToBurn = _amount.mul(burningPercentage).div(100);
if (amountToBurn > 0) {
assert(BurnableERC20(_token).burn(amountToBurn));
burnedTokens = burnedTokens.add(amountToBurn);
}
uint256 amountToTransfer = _amount.sub(amountToBurn);
if (amountToTransfer > 0) {
assert(BurnableERC20(_token).transfer(wallet, amountToTransfer));
transferredTokens = transferredTokens.add(amountToTransfer);
}
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol
/**
* @title DetailedERC20 token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, value));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/TokenTimelock.sol
/**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a given release time
*/
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
// ERC20 basic token contract being held
ERC20Basic public token;
// beneficiary of tokens after they are released
address public beneficiary;
// timestamp when token release is enabled
uint256 public releaseTime;
constructor(
ERC20Basic _token,
address _beneficiary,
uint256 _releaseTime
)
public
{
// solium-disable-next-line security/no-block-members
require(_releaseTime > block.timestamp);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= releaseTime);
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/TokenVesting.sol
/* solium-disable security/no-block-members */
pragma solidity ^0.4.23;
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
emit Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
// File: contracts/NokuCustomERC20.sol
/**
* @dev The NokuCustomERC20Token contract is a custom ERC20-compliant token available in the Noku Service Platform (NSP).
* The Noku customer is able to choose the token name, symbol, decimals, initial supply and to administer its lifecycle
* by minting or burning tokens in order to increase or decrease the token supply.
*/
contract NokuCustomERC20 is NokuCustomToken, DetailedERC20, MintableToken, BurnableToken {
using SafeMath for uint256;
event LogNokuCustomERC20Created(
address indexed caller,
string indexed name,
string indexed symbol,
uint8 decimals,
uint256 transferableFromBlock,
uint256 lockEndBlock,
address pricingPlan,
address serviceProvider
);
event LogMintingFeeEnabledChanged(address indexed caller, bool indexed mintingFeeEnabled);
event LogInformationChanged(address indexed caller, string name, string symbol);
event LogTransferFeePaymentFinished(address indexed caller);
event LogTransferFeePercentageChanged(address indexed caller, uint256 indexed transferFeePercentage);
// Flag indicating if minting fees are enabled or disabled
bool public mintingFeeEnabled;
// Block number from which tokens are initially transferable
uint256 public transferableFromBlock;
// Block number from which initial lock ends
uint256 public lockEndBlock;
// The initially locked balances by address
mapping (address => uint256) public initiallyLockedBalanceOf;
// The fee percentage for Custom Token transfer or zero if transfer is free of charge
uint256 public transferFeePercentage;
// Flag indicating if fee payment in Custom Token transfer has been permanently finished or not.
bool public transferFeePaymentFinished;
// Address of optional Timelock smart contract, otherwise 0x0
TokenTimelock public timelock;
// Address of optional Vesting smart contract, otherwise 0x0
TokenVesting public vesting;
bytes32 public constant BURN_SERVICE_NAME = "NokuCustomERC20.burn";
bytes32 public constant MINT_SERVICE_NAME = "NokuCustomERC20.mint";
bytes32 public constant TIMELOCK_SERVICE_NAME = "NokuCustomERC20.timelock";
bytes32 public constant VESTING_SERVICE_NAME = "NokuCustomERC20.vesting";
modifier canTransfer(address _from, uint _value) {
require(block.number >= transferableFromBlock, "token not transferable");
if (block.number < lockEndBlock) {
uint256 locked = lockedBalanceOf(_from);
if (locked > 0) {
uint256 newBalance = balanceOf(_from).sub(_value);
require(newBalance >= locked, "_value exceeds locked amount");
}
}
_;
}
constructor(
string _name,
string _symbol,
uint8 _decimals,
uint256 _transferableFromBlock,
uint256 _lockEndBlock,
address _pricingPlan,
address _serviceProvider
)
NokuCustomToken(_pricingPlan, _serviceProvider)
DetailedERC20(_name, _symbol, _decimals) public
{
require(bytes(_name).length > 0, "_name is empty");
require(bytes(_symbol).length > 0, "_symbol is empty");
require(_lockEndBlock >= _transferableFromBlock, "_lockEndBlock lower than _transferableFromBlock");
transferableFromBlock = _transferableFromBlock;
lockEndBlock = _lockEndBlock;
mintingFeeEnabled = true;
emit LogNokuCustomERC20Created(
msg.sender,
_name,
_symbol,
_decimals,
_transferableFromBlock,
_lockEndBlock,
_pricingPlan,
_serviceProvider
);
}
function setMintingFeeEnabled(bool _mintingFeeEnabled) public onlyOwner returns(bool successful) {
require(_mintingFeeEnabled != mintingFeeEnabled, "_mintingFeeEnabled == mintingFeeEnabled");
mintingFeeEnabled = _mintingFeeEnabled;
emit LogMintingFeeEnabledChanged(msg.sender, _mintingFeeEnabled);
return true;
}
/**
* @dev Change the Custom Token detailed information after creation.
* @param _name The name to assign to the Custom Token.
* @param _symbol The symbol to assign to the Custom Token.
*/
function setInformation(string _name, string _symbol) public onlyOwner returns(bool successful) {
require(bytes(_name).length > 0, "_name is empty");
require(bytes(_symbol).length > 0, "_symbol is empty");
name = _name;
symbol = _symbol;
emit LogInformationChanged(msg.sender, _name, _symbol);
return true;
}
/**
* @dev Stop trasfer fee payment for tokens.
* @return true if the operation was successful.
*/
function finishTransferFeePayment() public onlyOwner returns(bool finished) {
require(!transferFeePaymentFinished, "transfer fee finished");
transferFeePaymentFinished = true;
emit LogTransferFeePaymentFinished(msg.sender);
return true;
}
/**
* @dev Change the transfer fee percentage to be paid in Custom tokens.
* @param _transferFeePercentage The fee percentage to be paid for transfer in range [0, 100].
*/
function setTransferFeePercentage(uint256 _transferFeePercentage) public onlyOwner {
require(0 <= _transferFeePercentage && _transferFeePercentage <= 100, "_transferFeePercentage not in [0, 100]");
require(_transferFeePercentage != transferFeePercentage, "_transferFeePercentage equal to current value");
transferFeePercentage = _transferFeePercentage;
emit LogTransferFeePercentageChanged(msg.sender, _transferFeePercentage);
}
function lockedBalanceOf(address _to) public view returns(uint256 locked) {
uint256 initiallyLocked = initiallyLockedBalanceOf[_to];
if (block.number >= lockEndBlock) return 0;
else if (block.number <= transferableFromBlock) return initiallyLocked;
uint256 releaseForBlock = initiallyLocked.div(lockEndBlock.sub(transferableFromBlock));
uint256 released = block.number.sub(transferableFromBlock).mul(releaseForBlock);
return initiallyLocked.sub(released);
}
/**
* @dev Get the fee to be paid for the transfer of NOKU tokens.
* @param _value The amount of NOKU tokens to be transferred.
*/
function transferFee(uint256 _value) public view returns(uint256 usageFee) {
return _value.mul(transferFeePercentage).div(100);
}
/**
* @dev Check if token transfer is free of any charge or not.
* @return true if transfer is free of any charge.
*/
function freeTransfer() public view returns (bool isTransferFree) {
return transferFeePaymentFinished || transferFeePercentage == 0;
}
/**
* @dev Override #transfer for optionally paying fee to Custom token owner.
*/
function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns(bool transferred) {
if (freeTransfer()) {
return super.transfer(_to, _value);
}
else {
uint256 usageFee = transferFee(_value);
uint256 netValue = _value.sub(usageFee);
bool feeTransferred = super.transfer(owner, usageFee);
bool netValueTransferred = super.transfer(_to, netValue);
return feeTransferred && netValueTransferred;
}
}
/**
* @dev Override #transferFrom for optionally paying fee to Custom token owner.
*/
function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns(bool transferred) {
if (freeTransfer()) {
return super.transferFrom(_from, _to, _value);
}
else {
uint256 usageFee = transferFee(_value);
uint256 netValue = _value.sub(usageFee);
bool feeTransferred = super.transferFrom(_from, owner, usageFee);
bool netValueTransferred = super.transferFrom(_from, _to, netValue);
return feeTransferred && netValueTransferred;
}
}
/**
* @dev Burn a specific amount of tokens, paying the service fee.
* @param _amount The amount of token to be burned.
*/
function burn(uint256 _amount) public canBurn {
require(_amount > 0, "_amount is zero");
super.burn(_amount);
require(pricingPlan.payFee(BURN_SERVICE_NAME, _amount, msg.sender), "burn fee failed");
}
/**
* @dev Mint a specific amount of tokens, paying the service fee.
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) {
require(_to != 0, "_to is zero");
require(_amount > 0, "_amount is zero");
super.mint(_to, _amount);
if (mintingFeeEnabled) {
require(pricingPlan.payFee(MINT_SERVICE_NAME, _amount, msg.sender), "mint fee failed");
}
return true;
}
/**
* @dev Mint new locked tokens, which will unlock progressively.
* @param _to The address that will receieve the minted locked tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mintLocked(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) {
initiallyLockedBalanceOf[_to] = initiallyLockedBalanceOf[_to].add(_amount);
return mint(_to, _amount);
}
/**
* @dev Mint the specified amount of timelocked tokens.
* @param _to The address that will receieve the minted locked tokens.
* @param _amount The amount of tokens to mint.
* @param _releaseTime The token release time as timestamp from Unix epoch.
* @return A boolean that indicates if the operation was successful.
*/
function mintTimelocked(address _to, uint256 _amount, uint256 _releaseTime) public onlyOwner canMint
returns(bool minted)
{
require(timelock == address(0), "TokenTimelock already activated");
timelock = new TokenTimelock(this, _to, _releaseTime);
minted = mint(timelock, _amount);
require(pricingPlan.payFee(TIMELOCK_SERVICE_NAME, _amount, msg.sender), "timelock fee failed");
}
/**
* @dev Mint the specified amount of vested tokens.
* @param _to The address that will receieve the minted vested tokens.
* @param _amount The amount of tokens to mint.
* @param _startTime When the vesting starts as timestamp in seconds from Unix epoch.
* @param _duration The duration in seconds of the period in which the tokens will vest.
* @return A boolean that indicates if the operation was successful.
*/
function mintVested(address _to, uint256 _amount, uint256 _startTime, uint256 _duration) public onlyOwner canMint
returns(bool minted)
{
require(vesting == address(0), "TokenVesting already activated");
vesting = new TokenVesting(_to, _startTime, 0, _duration, true);
minted = mint(vesting, _amount);
require(pricingPlan.payFee(VESTING_SERVICE_NAME, _amount, msg.sender), "vesting fee failed");
}
/**
* @dev Release vested tokens to the beneficiary. Anyone can release vested tokens.
* @return A boolean that indicates if the operation was successful.
*/
function releaseVested() public returns(bool released) {
require(vesting != address(0), "TokenVesting not activated");
vesting.release(this);
return true;
}
/**
* @dev Revoke vested tokens. Just the token can revoke because it is the vesting owner.
* @return A boolean that indicates if the operation was successful.
*/
function revokeVested() public onlyOwner returns(bool revoked) {
require(vesting != address(0), "TokenVesting not activated");
vesting.revoke(this);
return true;
}
}
// File: contracts/TokenCappedCrowdsale.sol
/**
* @title CappedCrowdsale
* @dev Extension of Crowsdale with a max amount of funds raised
*/
contract TokenCappedCrowdsale is Crowdsale {
using SafeMath for uint256;
// The maximum token cap, should be initialized in derived contract
uint256 public tokenCap;
// Overriding Crowdsale#hasEnded to add tokenCap logic
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
bool capReached = soldTokens >= tokenCap;
return super.hasEnded() || capReached;
}
// Overriding Crowdsale#isValidPurchase to add extra cap logic
// @return true if investors can buy at the moment
function isValidPurchase(address beneficiary) internal view returns (bool isValid) {
uint256 tokenAmount = calculateTokens(msg.value);
bool withinCap = soldTokens.add(tokenAmount) <= tokenCap;
return withinCap && super.isValidPurchase(beneficiary);
}
}
// File: contracts/NokuCustomCrowdsale.sol
/**
* @title NokuCustomCrowdsale
* @dev Extension of TokenCappedCrowdsale using values specific for Noku Custom ICO crowdsale
*/
contract NokuCustomCrowdsale is TokenCappedCrowdsale {
using AddressUtils for address;
using SafeMath for uint256;
event LogNokuCustomCrowdsaleCreated(
address sender,
uint256 indexed startBlock,
uint256 indexed endBlock,
address indexed wallet
);
event LogThreePowerAgesChanged(
address indexed sender,
uint256 indexed platinumAgeEndBlock,
uint256 indexed goldenAgeEndBlock,
uint256 silverAgeEndBlock,
uint256 platinumAgeRate,
uint256 goldenAgeRate,
uint256 silverAgeRate
);
event LogTwoPowerAgesChanged(
address indexed sender,
uint256 indexed platinumAgeEndBlock,
uint256 indexed goldenAgeEndBlock,
uint256 platinumAgeRate,
uint256 goldenAgeRate
);
event LogOnePowerAgeChanged(address indexed sender, uint256 indexed platinumAgeEndBlock, uint256 indexed platinumAgeRate);
// The end block of the 'platinum' age interval
uint256 public platinumAgeEndBlock;
// The end block of the 'golden' age interval
uint256 public goldenAgeEndBlock;
// The end block of the 'silver' age interval
uint256 public silverAgeEndBlock;
// The conversion rate of the 'platinum' age
uint256 public platinumAgeRate;
// The conversion rate of the 'golden' age
uint256 public goldenAgeRate;
// The conversion rate of the 'silver' age
uint256 public silverAgeRate;
// The wallet address or contract
address public wallet;
constructor(
uint256 _startBlock,
uint256 _endBlock,
uint256 _rate,
uint256 _minDeposit,
uint256 _maxWhitelistLength,
uint256 _whitelistThreshold,
address _token,
uint256 _tokenMaximumSupply,
address _wallet
)
Crowdsale(
_startBlock,
_endBlock,
_rate,
_minDeposit,
_maxWhitelistLength,
_whitelistThreshold
)
public {
require(_token.isContract(), "_token is not contract");
require(_tokenMaximumSupply > 0, "_tokenMaximumSupply is zero");
platinumAgeRate = _rate;
goldenAgeRate = _rate;
silverAgeRate = _rate;
token = NokuCustomERC20(_token);
wallet = _wallet;
// Assume predefined token supply has been minted and calculate the maximum number of tokens that can be sold
tokenCap = _tokenMaximumSupply.sub(token.totalSupply());
emit LogNokuCustomCrowdsaleCreated(msg.sender, startBlock, endBlock, _wallet);
}
function setThreePowerAges(
uint256 _platinumAgeEndBlock,
uint256 _goldenAgeEndBlock,
uint256 _silverAgeEndBlock,
uint256 _platinumAgeRate,
uint256 _goldenAgeRate,
uint256 _silverAgeRate
)
external onlyOwner beforeStart
{
require(startBlock < _platinumAgeEndBlock, "_platinumAgeEndBlock not greater than start block");
require(_platinumAgeEndBlock < _goldenAgeEndBlock, "_platinumAgeEndBlock not lower than _goldenAgeEndBlock");
require(_goldenAgeEndBlock < _silverAgeEndBlock, "_silverAgeEndBlock not greater than _goldenAgeEndBlock");
require(_silverAgeEndBlock <= endBlock, "_silverAgeEndBlock greater than end block");
require(_platinumAgeRate > _goldenAgeRate, "_platinumAgeRate not greater than _goldenAgeRate");
require(_goldenAgeRate > _silverAgeRate, "_goldenAgeRate not greater than _silverAgeRate");
require(_silverAgeRate > rate, "_silverAgeRate not greater than nominal rate");
platinumAgeEndBlock = _platinumAgeEndBlock;
goldenAgeEndBlock = _goldenAgeEndBlock;
silverAgeEndBlock = _silverAgeEndBlock;
platinumAgeRate = _platinumAgeRate;
goldenAgeRate = _goldenAgeRate;
silverAgeRate = _silverAgeRate;
emit LogThreePowerAgesChanged(
msg.sender,
_platinumAgeEndBlock,
_goldenAgeEndBlock,
_silverAgeEndBlock,
_platinumAgeRate,
_goldenAgeRate,
_silverAgeRate
);
}
function setTwoPowerAges(
uint256 _platinumAgeEndBlock,
uint256 _goldenAgeEndBlock,
uint256 _platinumAgeRate,
uint256 _goldenAgeRate
)
external onlyOwner beforeStart
{
require(startBlock < _platinumAgeEndBlock, "_platinumAgeEndBlock not greater than start block");
require(_platinumAgeEndBlock < _goldenAgeEndBlock, "_platinumAgeEndBlock not lower than _goldenAgeEndBlock");
require(_goldenAgeEndBlock <= endBlock, "_goldenAgeEndBlock greater than end block");
require(_platinumAgeRate > _goldenAgeRate, "_platinumAgeRate not greater than _goldenAgeRate");
require(_goldenAgeRate > rate, "_goldenAgeRate not greater than nominal rate");
platinumAgeEndBlock = _platinumAgeEndBlock;
goldenAgeEndBlock = _goldenAgeEndBlock;
platinumAgeRate = _platinumAgeRate;
goldenAgeRate = _goldenAgeRate;
silverAgeRate = rate;
emit LogTwoPowerAgesChanged(
msg.sender,
_platinumAgeEndBlock,
_goldenAgeEndBlock,
_platinumAgeRate,
_goldenAgeRate
);
}
function setOnePowerAge(uint256 _platinumAgeEndBlock, uint256 _platinumAgeRate)
external onlyOwner beforeStart
{
require(startBlock < _platinumAgeEndBlock, "_platinumAgeEndBlock not greater than start block");
require(_platinumAgeEndBlock <= endBlock, "_platinumAgeEndBlock greater than end block");
require(_platinumAgeRate > rate, "_platinumAgeRate not greater than nominal rate");
platinumAgeEndBlock = _platinumAgeEndBlock;
platinumAgeRate = _platinumAgeRate;
goldenAgeRate = rate;
silverAgeRate = rate;
emit LogOnePowerAgeChanged(msg.sender, _platinumAgeEndBlock, _platinumAgeRate);
}
function grantTokenOwnership(address _client) external onlyOwner returns(bool granted) {
require(!_client.isContract(), "_client is contract");
require(hasEnded(), "crowdsale not ended yet");
// Transfer NokuCustomERC20 ownership back to the client
token.transferOwnership(_client);
return true;
}
// Overriding Crowdsale#calculateTokens to apply age discounts to token calculus.
function calculateTokens(uint256 amount) internal view returns(uint256 tokenAmount) {
uint256 conversionRate = block.number <= platinumAgeEndBlock ? platinumAgeRate :
block.number <= goldenAgeEndBlock ? goldenAgeRate :
block.number <= silverAgeEndBlock ? silverAgeRate :
rate;
return amount.mul(conversionRate);
}
/**
* @dev Overriding Crowdsale#distributeTokens to apply age rules to token distributions.
*/
function distributeTokens(address beneficiary, uint256 tokenAmount) internal {
if (block.number <= platinumAgeEndBlock) {
NokuCustomERC20(token).mintLocked(beneficiary, tokenAmount);
}
else {
super.distributeTokens(beneficiary, tokenAmount);
}
}
/**
* @dev Overriding Crowdsale#forwardFunds to split net/fee payment.
*/
function forwardFunds(uint256 amount) internal {
wallet.transfer(amount);
}
}
// File: contracts/NokuCustomService.sol
contract NokuCustomService is Pausable {
using AddressUtils for address;
event LogPricingPlanChanged(address indexed caller, address indexed pricingPlan);
// The pricing plan determining the fee to be paid in NOKU tokens by customers
NokuPricingPlan public pricingPlan;
constructor(address _pricingPlan) internal {
require(_pricingPlan.isContract(), "_pricingPlan is not contract");
pricingPlan = NokuPricingPlan(_pricingPlan);
}
function setPricingPlan(address _pricingPlan) public onlyOwner {
require(_pricingPlan.isContract(), "_pricingPlan is not contract");
require(NokuPricingPlan(_pricingPlan) != pricingPlan, "_pricingPlan equal to current");
pricingPlan = NokuPricingPlan(_pricingPlan);
emit LogPricingPlanChanged(msg.sender, _pricingPlan);
}
}
// File: contracts/NokuCustomCrowdsaleService.sol
/**
* @title NokuCustomCrowdsaleService
* @dev Extension of NokuCustomService adding the fee payment in NOKU tokens.
*/
contract NokuCustomCrowdsaleService is NokuCustomService {
event LogNokuCustomCrowdsaleServiceCreated(address indexed caller);
bytes32 public constant SERVICE_NAME = "NokuCustomERC20.crowdsale";
uint256 public constant CREATE_AMOUNT = 1 * 10**18;
constructor(address _pricingPlan) NokuCustomService(_pricingPlan) public {
emit LogNokuCustomCrowdsaleServiceCreated(msg.sender);
}
function createCustomCrowdsale(
uint256 _startBlock,
uint256 _endBlock,
uint256 _rate,
uint256 _minDeposit,
uint256 _maxWhitelistLength,
uint256 _whitelistThreshold,
address _token,
uint256 _tokenMaximumSupply,
address _wallet
)
public returns(NokuCustomCrowdsale customCrowdsale)
{
customCrowdsale = new NokuCustomCrowdsale(
_startBlock,
_endBlock,
_rate,
_minDeposit,
_maxWhitelistLength,
_whitelistThreshold,
_token,
_tokenMaximumSupply,
_wallet
);
// Transfer NokuCustomCrowdsale ownership to the client
customCrowdsale.transferOwnership(msg.sender);
require(pricingPlan.payFee(SERVICE_NAME, CREATE_AMOUNT, msg.sender), "fee payment failed");
}
} | * @title Crowdsale @dev Crowdsale is a base contract for managing a token crowdsale. Crowdsales have a start and end block, where investors can make token purchases and the crowdsale will assign them tokens based on a token per ETH rate. Funds collected are forwarded to a wallet as they arrive./ The token being sold The start and end block where investments are allowed (both inclusive) How many token units a buyer gets per wei Amount of raised money in wei Amount of tokens already sold Balances in wei deposited by each subscriber The minimum balance for each subscriber in wei | contract Crowdsale is TokenSale, Pausable, Whitelistable {
using AddressUtils for address;
using SafeMath for uint256;
event LogStartBlockChanged(uint256 indexed startBlock);
event LogEndBlockChanged(uint256 indexed endBlock);
event LogMinDepositChanged(uint256 indexed minDeposit);
event LogTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 indexed amount, uint256 tokenAmount);
MintableToken public token;
uint256 public startBlock;
uint256 public endBlock;
uint256 public rate;
uint256 public raisedFunds;
uint256 public soldTokens;
mapping (address => uint256) public balanceOf;
uint256 public minDeposit;
modifier beforeStart() {
require(block.number < startBlock, "already started");
_;
}
modifier beforeEnd() {
require(block.number <= endBlock, "already ended");
_;
}
constructor(
uint256 _startBlock,
uint256 _endBlock,
uint256 _rate,
uint256 _minDeposit,
uint256 maxWhitelistLength,
uint256 whitelistThreshold
)
Whitelistable(maxWhitelistLength, whitelistThreshold) internal
{
require(_startBlock >= block.number, "_startBlock is lower than current block.number");
require(_endBlock >= _startBlock, "_endBlock is lower than _startBlock");
require(_rate > 0, "_rate is zero");
require(_minDeposit > 0, "_minDeposit is zero");
startBlock = _startBlock;
endBlock = _endBlock;
rate = _rate;
minDeposit = _minDeposit;
}
function hasStarted() public view returns (bool started) {
return block.number >= startBlock;
}
function hasEnded() public view returns (bool ended) {
return block.number > endBlock;
}
function setStartBlock(uint256 _startBlock) external onlyOwner beforeStart {
require(_startBlock >= block.number, "_startBlock < current block");
require(_startBlock <= endBlock, "_startBlock > endBlock");
require(_startBlock != startBlock, "_startBlock == startBlock");
startBlock = _startBlock;
emit LogStartBlockChanged(_startBlock);
}
function setEndBlock(uint256 _endBlock) external onlyOwner beforeEnd {
require(_endBlock >= block.number, "_endBlock < current block");
require(_endBlock >= startBlock, "_endBlock < startBlock");
require(_endBlock != endBlock, "_endBlock == endBlock");
endBlock = _endBlock;
emit LogEndBlockChanged(_endBlock);
}
function setMinDeposit(uint256 _minDeposit) external onlyOwner beforeEnd {
require(0 < _minDeposit && _minDeposit < minDeposit, "_minDeposit is not in [0, minDeposit]");
minDeposit = _minDeposit;
emit LogMinDepositChanged(minDeposit);
}
function setMaxWhitelistLength(uint256 maxWhitelistLength) external onlyOwner beforeEnd {
setMaxWhitelistLengthInternal(maxWhitelistLength);
}
function setWhitelistThresholdBalance(uint256 whitelistThreshold) external onlyOwner beforeEnd {
setWhitelistThresholdBalanceInternal(whitelistThreshold);
}
function addToWhitelist(address subscriber) external onlyOwner beforeEnd {
addToWhitelistInternal(subscriber);
}
function removeFromWhitelist(address subscriber) external onlyOwner beforeEnd {
removeFromWhitelistInternal(subscriber, balanceOf[subscriber]);
}
function () external payable whenNotPaused {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable whenNotPaused {
require(beneficiary != address(0), "beneficiary is zero");
require(isValidPurchase(beneficiary), "invalid purchase by beneficiary");
balanceOf[beneficiary] = balanceOf[beneficiary].add(msg.value);
raisedFunds = raisedFunds.add(msg.value);
uint256 tokenAmount = calculateTokens(msg.value);
soldTokens = soldTokens.add(tokenAmount);
distributeTokens(beneficiary, tokenAmount);
emit LogTokenPurchase(msg.sender, beneficiary, msg.value, tokenAmount);
forwardFunds(msg.value);
}
function isAllowedBalance(address beneficiary, uint256 balance) public view returns (bool isReallyAllowed) {
bool hasMinimumBalance = balance >= minDeposit;
return hasMinimumBalance && super.isAllowedBalance(beneficiary, balance);
}
function isValidPurchase(address beneficiary) internal view returns (bool isValid) {
bool withinPeriod = startBlock <= block.number && block.number <= endBlock;
bool nonZeroPurchase = msg.value != 0;
bool isValidBalance = isAllowedBalance(beneficiary, balanceOf[beneficiary].add(msg.value));
return withinPeriod && nonZeroPurchase && isValidBalance;
}
function calculateTokens(uint256 amount) internal view returns (uint256 tokenAmount) {
return amount.mul(rate);
}
function distributeTokens(address beneficiary, uint256 tokenAmount) internal {
token.mint(beneficiary, tokenAmount);
}
}
| 5,824,716 | [
1,
39,
492,
2377,
5349,
225,
385,
492,
2377,
5349,
353,
279,
1026,
6835,
364,
30632,
279,
1147,
276,
492,
2377,
5349,
18,
385,
492,
2377,
5408,
1240,
279,
787,
471,
679,
1203,
16,
1625,
2198,
395,
1383,
848,
1221,
1147,
5405,
343,
3304,
471,
326,
276,
492,
2377,
5349,
903,
2683,
2182,
2430,
2511,
603,
279,
1147,
1534,
512,
2455,
4993,
18,
478,
19156,
12230,
854,
19683,
358,
279,
9230,
487,
2898,
2454,
688,
18,
19,
1021,
1147,
3832,
272,
1673,
1021,
787,
471,
679,
1203,
1625,
2198,
395,
1346,
854,
2935,
261,
18237,
13562,
13,
9017,
4906,
1147,
4971,
279,
27037,
5571,
1534,
732,
77,
16811,
434,
11531,
15601,
316,
732,
77,
16811,
434,
2430,
1818,
272,
1673,
605,
26488,
316,
732,
77,
443,
1724,
329,
635,
1517,
9467,
1021,
5224,
11013,
364,
1517,
9467,
316,
732,
77,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
385,
492,
2377,
5349,
353,
3155,
30746,
16,
21800,
16665,
16,
3497,
7523,
429,
288,
203,
565,
1450,
5267,
1989,
364,
1758,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
871,
1827,
1685,
1768,
5033,
12,
11890,
5034,
8808,
787,
1768,
1769,
203,
565,
871,
1827,
1638,
1768,
5033,
12,
11890,
5034,
8808,
679,
1768,
1769,
203,
565,
871,
1827,
2930,
758,
1724,
5033,
12,
11890,
5034,
8808,
1131,
758,
1724,
1769,
203,
565,
871,
1827,
1345,
23164,
12,
2867,
8808,
5405,
343,
14558,
16,
1758,
8808,
27641,
74,
14463,
814,
16,
2254,
5034,
8808,
3844,
16,
2254,
5034,
1147,
6275,
1769,
203,
203,
565,
490,
474,
429,
1345,
1071,
1147,
31,
203,
203,
565,
2254,
5034,
1071,
787,
1768,
31,
203,
565,
2254,
5034,
1071,
679,
1768,
31,
203,
203,
565,
2254,
5034,
1071,
4993,
31,
203,
203,
565,
2254,
5034,
1071,
11531,
42,
19156,
31,
203,
203,
565,
2254,
5034,
1071,
272,
1673,
5157,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
11013,
951,
31,
203,
203,
565,
2254,
5034,
1071,
1131,
758,
1724,
31,
203,
203,
203,
565,
9606,
1865,
1685,
1435,
288,
203,
3639,
2583,
12,
2629,
18,
2696,
411,
787,
1768,
16,
315,
17583,
5746,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1865,
1638,
1435,
288,
203,
3639,
2583,
12,
2629,
18,
2696,
1648,
679,
1768,
16,
315,
17583,
16926,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
12,
203,
2
] |
./full_match/97/0xd3Cc2d78CF596e027ab31FFc5FB66222F29EA748/sources/project_/contracts/Vesting.sol | @notice Calculate the vested and unclaimed months and tokens available for `_grantId` to claim Due to rounding errors once grant duration is reached, returns the entire left grant amount Returns (0, 0) if lock duration has not been reached Check if lock duration was reached by comparing the current time with the startTime. If lock duration hasn't been reached, return 0, 0 If over vesting duration, all tokens vested | function calculateGrantClaim(address _recipient) public view returns (uint256, uint256) {
Grant storage tokenGrant = tokenGrants[_recipient];
require(tokenGrant.totalClaimed < tokenGrant.amount, "Grant fully claimed");
if (currentTime() < startTime || startTime == 0) {
return (0, 0);
}
if (elapsedMonths > tokenGrant.vestingDuration) {
uint256 remainingGrant = tokenGrant.amount.sub(tokenGrant.totalClaimed);
uint256 balanceMonth = tokenGrant.vestingDuration.sub(tokenGrant.monthsClaimed);
return (balanceMonth, remainingGrant);
uint256 monthsVested = uint256(elapsedMonths.sub(tokenGrant.monthsClaimed));
uint256 amountVestedPerMonth = (tokenGrant.amount.sub(tokenGrant.totalClaimed)).div(uint256(tokenGrant.vestingDuration.sub(tokenGrant.monthsClaimed)));
uint256 amountVested = uint256(monthsVested.mul(amountVestedPerMonth));
return (monthsVested, amountVested);
}
}
| 3,279,175 | [
1,
8695,
326,
331,
3149,
471,
6301,
80,
4581,
329,
8846,
471,
2430,
2319,
364,
1375,
67,
16243,
548,
68,
358,
7516,
463,
344,
358,
13885,
1334,
3647,
7936,
3734,
353,
8675,
16,
1135,
326,
7278,
2002,
7936,
3844,
2860,
261,
20,
16,
374,
13,
309,
2176,
3734,
711,
486,
2118,
8675,
2073,
309,
2176,
3734,
1703,
8675,
635,
17553,
326,
783,
813,
598,
326,
8657,
18,
971,
2176,
3734,
13342,
1404,
2118,
8675,
16,
327,
374,
16,
374,
971,
1879,
331,
10100,
3734,
16,
777,
2430,
331,
3149,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4604,
9021,
9762,
12,
2867,
389,
20367,
13,
1071,
1476,
1135,
261,
11890,
5034,
16,
2254,
5034,
13,
288,
203,
3639,
19689,
2502,
1147,
9021,
273,
1147,
29598,
63,
67,
20367,
15533,
203,
203,
3639,
2583,
12,
2316,
9021,
18,
4963,
9762,
329,
411,
1147,
9021,
18,
8949,
16,
315,
9021,
7418,
7516,
329,
8863,
203,
203,
3639,
309,
261,
2972,
950,
1435,
411,
8657,
747,
8657,
422,
374,
13,
288,
203,
5411,
327,
261,
20,
16,
374,
1769,
203,
3639,
289,
203,
203,
3639,
309,
261,
26201,
19749,
405,
1147,
9021,
18,
90,
10100,
5326,
13,
288,
203,
5411,
2254,
5034,
4463,
9021,
273,
1147,
9021,
18,
8949,
18,
1717,
12,
2316,
9021,
18,
4963,
9762,
329,
1769,
203,
5411,
2254,
5034,
11013,
5445,
273,
1147,
9021,
18,
90,
10100,
5326,
18,
1717,
12,
2316,
9021,
18,
27584,
9762,
329,
1769,
203,
5411,
327,
261,
12296,
5445,
16,
4463,
9021,
1769,
203,
5411,
2254,
5034,
8846,
58,
3149,
273,
2254,
5034,
12,
26201,
19749,
18,
1717,
12,
2316,
9021,
18,
27584,
9762,
329,
10019,
203,
5411,
2254,
5034,
3844,
58,
3149,
2173,
5445,
273,
261,
2316,
9021,
18,
8949,
18,
1717,
12,
2316,
9021,
18,
4963,
9762,
329,
13,
2934,
2892,
12,
11890,
5034,
12,
2316,
9021,
18,
90,
10100,
5326,
18,
1717,
12,
2316,
9021,
18,
27584,
9762,
329,
3719,
1769,
203,
5411,
2254,
5034,
3844,
58,
3149,
273,
2254,
5034,
12,
27584,
58,
3149,
18,
16411,
12,
8949,
58,
3149,
2173,
5445,
10019,
203,
5411,
327,
261,
27584,
58,
2
] |
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity >=0.4.22 <0.9.0;
contract Music {
// List of Song titles
string[] public songTitles;
string[] public songHashes;
string[] public artists;
string[] public bestSongs;
songLikes[] public song_likes;
artistLikes[] public artist_likes;
// Map the artist to the song
mapping(string => Music_data[]) public artist_song_mapping;
// Map the genre to the song
mapping(string => Music_data[]) public genre_song_mapping;
// listeners list
listenerCount[] public listener_count;
struct songLikes {
string songName;
uint256 likes;
}
struct listenerCount {
address listener;
uint256 count;
}
struct artistLikes {
string artistName;
uint256 likes;
}
struct Music_data {
string songTitle;
string songProducer;
string songArtist;
string songDate;
string genre;
string albumName;
string hash_;
uint256 likes;
address[] likedBy;
}
constructor() {}
function songExists(string memory title) private view returns (bool) {
for (uint256 i = 0; i < songTitles.length; i++) {
if (keccak256(bytes(songTitles[i])) == keccak256(bytes(title))) {
return true;
}
}
return false;
}
function songHashExists(string memory hash_) private view returns (bool) {
for (uint256 i = 0; i < songHashes.length; i++) {
if (keccak256(bytes(songHashes[i])) == keccak256(bytes(hash_))) {
return true;
}
}
return false;
}
function artistExists(string memory _name) private view returns (bool) {
for (uint256 i = 0; i < artists.length; i++) {
if (keccak256(bytes(artists[i])) == keccak256(bytes(_name))) {
return true;
}
}
return false;
}
modifier onlyUniqueHash(string memory _hash) {
require(!songHashExists(_hash));
_;
}
modifier onlyUniqueSongTitle(string memory _name) {
require(!songExists(_name));
_;
}
modifier validArtist(string memory _name) {
require(artistExists(_name));
_;
}
modifier validSong(string memory _song) {
require(songExists(_song));
_;
}
function getAllArtists() public view returns (string[] memory) {
return artists;
}
function getAllSongs() public view returns (string[] memory) {
return songTitles;
}
function getArtistSongs(string memory artistName)
public
view
validArtist(artistName)
returns (string[] memory)
{
string[] memory songsOfArtist = new string[](
artist_song_mapping[artistName].length
);
for (uint256 i = 0; i < artist_song_mapping[artistName].length; i++) {
songsOfArtist[i] = artist_song_mapping[artistName][i].songTitle;
}
return songsOfArtist;
// return artist_song_mapping[artistName];
}
function getSongsArtist(string memory songName)
public
view
validSong(songName)
returns (string memory artistName)
{
// string memory artistName;
for (uint256 i = 0; i < artists.length; i++) {
for (
uint256 j = 0;
j < artist_song_mapping[artists[i]].length;
j++
) {
if (
keccak256(
bytes(artist_song_mapping[artists[i]][j].songTitle)
) == keccak256(bytes(songName))
) {
artistName = artist_song_mapping[artists[i]][j].songArtist;
return artistName;
}
}
}
}
function getSongsProducer(string memory songName)
public
view
validSong(songName)
returns (string memory producer)
{
// string memory producer;
for (uint256 i = 0; i < artists.length; i++) {
for (
uint256 j = 0;
j < artist_song_mapping[artists[i]].length;
j++
) {
if (
keccak256(
bytes(artist_song_mapping[artists[i]][j].songTitle)
) == keccak256(bytes(songName))
) {
producer = artist_song_mapping[artists[i]][j].songProducer;
return producer;
}
}
}
}
function getSongsGenre(string memory songName)
public
view
validSong(songName)
returns (string memory genre)
{
// string memory genre;
for (uint256 i = 0; i < artists.length; i++) {
for (
uint256 j = 0;
j < artist_song_mapping[artists[i]].length;
j++
) {
if (
keccak256(
bytes(artist_song_mapping[artists[i]][j].songTitle)
) == keccak256(bytes(songName))
) {
genre = artist_song_mapping[artists[i]][j].genre;
return genre;
}
}
}
}
function getSongsAlbumName(string memory songName)
public
view
validSong(songName)
returns (string memory aname)
{
// string memory aname;
for (uint256 i = 0; i < artists.length; i++) {
for (
uint256 j = 0;
j < artist_song_mapping[artists[i]].length;
j++
) {
if (
keccak256(
bytes(artist_song_mapping[artists[i]][j].songTitle)
) == keccak256(bytes(songName))
) {
aname = artist_song_mapping[artists[i]][j].albumName;
return aname;
}
}
}
}
function getSongsLikes(string memory songName)
public
view
validSong(songName)
returns (uint256 likes)
{
// uint likes;
for (uint256 i = 0; i < artists.length; i++) {
for (
uint256 j = 0;
j < artist_song_mapping[artists[i]].length;
j++
) {
if (
keccak256(
bytes(artist_song_mapping[artists[i]][j].songTitle)
) == keccak256(bytes(songName))
) {
likes = artist_song_mapping[artists[i]][j].likes;
return likes;
}
}
}
}
function getSongsDate(string memory songName)
public
view
validSong(songName)
returns (string memory date_val)
{
// string memory date_val;
for (uint256 i = 0; i < artists.length; i++) {
for (
uint256 j = 0;
j < artist_song_mapping[artists[i]].length;
j++
) {
if (
keccak256(
bytes(artist_song_mapping[artists[i]][j].songTitle)
) == keccak256(bytes(songName))
) {
date_val = artist_song_mapping[artists[i]][j].songDate;
return date_val;
}
}
}
}
function getGenreSongs(string memory _genre)
public
view
returns (Music_data[] memory)
{
return genre_song_mapping[_genre];
}
function hasAlreadyBeenLiked(
address personAddr,
string memory _artist,
uint256 i
) private view returns (bool) {
for (
uint256 k = 0;
k < artist_song_mapping[_artist][i].likedBy.length;
k++
) {
if (artist_song_mapping[_artist][i].likedBy[k] == personAddr) {
return true;
}
}
return false;
}
function likeSong(string memory _artist, string memory _song)
public
validSong(_song)
validArtist(_artist)
{
for (uint256 i = 0; i < artist_song_mapping[_artist].length; i++) {
if (
keccak256(bytes(artist_song_mapping[_artist][i].songTitle)) ==
keccak256(bytes(_song))
) {
artist_song_mapping[_artist][i].likes += 1;
// Check if the user hasn't previously liked this song
require(!hasAlreadyBeenLiked(msg.sender, _artist, i));
artist_song_mapping[_artist][i].likedBy.push(msg.sender);
bool found = false;
for (uint256 x = 0; x < song_likes.length; x++) {
if (
keccak256(bytes(song_likes[x].songName)) ==
keccak256(bytes(_song))
) {
song_likes[x].likes += 1; // Increment the likes
found = true;
}
}
// If song not already in the songs list then add them here
if (!found) {
song_likes.push(
songLikes(
artist_song_mapping[_artist][i].songTitle,
artist_song_mapping[_artist][i].likes
)
);
}
found = false;
for (uint256 x = 0; x < artist_likes.length; x++) {
if (
keccak256(bytes(artist_likes[x].artistName)) ==
keccak256(bytes(_artist))
) {
artist_likes[x].likes += 1; // Increment the likes
found = true;
}
}
// If song not already in the songs list then add them here
if (!found) {
artist_likes.push(
artistLikes(
artist_song_mapping[_artist][i].songArtist,
artist_song_mapping[_artist][i].likes
)
);
}
}
}
}
function quickSort(
songLikes[] memory arr,
int256 left,
int256 right
) private pure {
int256 i = left;
int256 j = right;
if (i == j) return;
uint256 pivot = arr[uint256(left + (right - left) / 2)].likes;
while (i <= j) {
while (arr[uint256(i)].likes > pivot) i++;
while (pivot > arr[uint256(j)].likes) j--;
if (i <= j) {
(arr[uint256(i)], arr[uint256(j)]) = (
arr[uint256(j)],
arr[uint256(i)]
);
i++;
j--;
}
}
if (left < j) quickSort(arr, left, j);
if (i < right) quickSort(arr, i, right);
}
function quickSortListeners(
listenerCount[] memory arr,
int256 left,
int256 right
) private pure {
int256 i = left;
int256 j = right;
if (i == j) return;
uint256 pivot = arr[uint256(left + (right - left) / 2)].count;
while (i <= j) {
while (arr[uint256(i)].count > pivot) i++;
while (pivot > arr[uint256(j)].count) j--;
if (i <= j) {
(arr[uint256(i)], arr[uint256(j)]) = (
arr[uint256(j)],
arr[uint256(i)]
);
i++;
j--;
}
}
if (left < j) quickSortListeners(arr, left, j);
if (i < right) quickSortListeners(arr, i, right);
}
function quickSortArtists(
artistLikes[] memory arr,
int256 left,
int256 right
) private pure {
int256 i = left;
int256 j = right;
if (i == j) return;
uint256 pivot = arr[uint256(left + (right - left) / 2)].likes;
while (i <= j) {
while (arr[uint256(i)].likes > pivot) i++;
while (pivot > arr[uint256(j)].likes) j--;
if (i <= j) {
(arr[uint256(i)], arr[uint256(j)]) = (
arr[uint256(j)],
arr[uint256(i)]
);
i++;
j--;
}
}
if (left < j) quickSortArtists(arr, left, j);
if (i < right) quickSortArtists(arr, i, right);
}
function getTopKSongs(uint256 k) public view returns (songLikes[] memory) {
require(k <= song_likes.length);
songLikes[] memory songsList = new songLikes[](k);
songLikes[] memory songsLikesCopy = new songLikes[](song_likes.length);
for (uint256 z = 0; z < song_likes.length; z++) {
songsLikesCopy[z] = song_likes[z];
}
quickSort(songsLikesCopy, int256(0), int256(songsLikesCopy.length - 1));
for (uint256 i = 0; i < k; i++) {
songsList[i] = songsLikesCopy[i];
}
return songsList;
}
// Get top artists
function getTopArtists(uint256 k)
public
view
returns (artistLikes[] memory)
{
require(k <= artist_likes.length);
artistLikes[] memory artistsList = new artistLikes[](k);
artistLikes[] memory copyArtists = new artistLikes[](
artist_likes.length
);
for (uint256 z = 0; z < artists.length; z++) {
copyArtists[z] = artist_likes[z];
}
quickSortArtists(
copyArtists,
int256(0),
int256(copyArtists.length - 1)
);
// bubbleSort(listener_count);
for (uint256 x = 0; x < k; x++) {
artistsList[x] = (copyArtists[x]);
}
return artistsList;
}
// Add to listener count - will be used just to get top listeners
function listenToSong() public {
bool found = false;
for (uint256 j = 0; j < listener_count.length; j++) {
if (listener_count[j].listener == msg.sender) {
found = true;
listener_count[j].count += 1;
}
}
if (!found) {
listener_count.push(listenerCount(msg.sender, 1));
}
}
// Get top listeners
function getTopListeners(uint256 k)
public
view
returns (listenerCount[] memory)
{
require(k <= listener_count.length);
listenerCount[] memory listenersList = new listenerCount[](k);
listenerCount[] memory copyListeners = new listenerCount[](
listener_count.length
);
for (uint256 z = 0; z < listener_count.length; z++) {
copyListeners[z] = listener_count[z];
}
quickSortListeners(
copyListeners,
int256(0),
int256(copyListeners.length - 1)
);
// bubbleSort(listener_count);
for (uint256 x = 0; x < k; x++) {
listenersList[x] = (copyListeners[x]);
}
return listenersList;
}
function addMusicContent(
string memory _songTitle,
string memory _songProducer,
string memory _songArtist,
string memory _songDate,
string memory _genre,
string memory _albumName,
string memory _hash_
) public onlyUniqueHash(_hash_) onlyUniqueSongTitle(_songTitle) {
// Song Name and hash both do not exist before
songTitles.push(_songTitle);
songHashes.push(_hash_);
bool x = true;
//Only insert into artists array if not exists
for (uint256 i = 0; i < artists.length; i++) {
if (keccak256(bytes(artists[i])) == keccak256(bytes(_songArtist))) {
x = false;
}
}
if (x == true) {
artists.push(_songArtist);
}
address[] memory a;
// Map artist to song
artist_song_mapping[_songArtist].push(
Music_data(
_songTitle,
_songProducer,
_songArtist,
_songDate,
_genre,
_albumName,
_hash_,
0,
a
)
);
// Map genre to song
genre_song_mapping[_genre].push(
Music_data(
_songTitle,
_songProducer,
_songArtist,
_songDate,
_genre,
_albumName,
_hash_,
0,
a
)
);
}
function getURLofSong(string memory songName)
public
view
returns (string memory)
{
for (uint256 j = 0; j < artists.length; j++) {
for (
uint256 i = 0;
i < artist_song_mapping[artists[j]].length;
i++
) {
if (
keccak256(
bytes(artist_song_mapping[artists[j]][i].songTitle)
) == keccak256(bytes(songName))
) {
return artist_song_mapping[artists[j]][i].hash_;
}
}
}
return "";
}
}
// let myins = await Music.deployed()
// myins.listenToSong({from:accounts[0]})
// myins.addMusicContent('abc','as','Adil','dsf','sdf','sddf','234scvdw')
// myins.addMusicContent('abcd','as','Ali','dsf','sdf','sddf','234scvsdd')
// myins.addMusicContent('ab3c','as','Ali','dsf','sdf','sddf','234scved')
// myins.addMusicContent('aewbc','as','Ali','dsf','sdf','sddf','234sdscvd')
// myins.getArtistSongs('Adil')
// myins.likeSong('Adil', 'abc', {from:accounts[0]})
// myins.getAllArtists();
// myins.getAllSongs();
// myins.getTopKSongs(3);
| Add to listener count - will be used just to get top listeners | function listenToSong() public {
bool found = false;
for (uint256 j = 0; j < listener_count.length; j++) {
if (listener_count[j].listener == msg.sender) {
found = true;
listener_count[j].count += 1;
}
}
if (!found) {
listener_count.push(listenerCount(msg.sender, 1));
}
}
| 5,512,310 | [
1,
986,
358,
2991,
1056,
300,
903,
506,
1399,
2537,
358,
336,
1760,
4679,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6514,
774,
55,
932,
1435,
1071,
288,
203,
3639,
1426,
1392,
273,
629,
31,
203,
3639,
364,
261,
11890,
5034,
525,
273,
374,
31,
525,
411,
2991,
67,
1883,
18,
2469,
31,
525,
27245,
288,
203,
5411,
309,
261,
12757,
67,
1883,
63,
78,
8009,
12757,
422,
1234,
18,
15330,
13,
288,
203,
7734,
1392,
273,
638,
31,
203,
7734,
2991,
67,
1883,
63,
78,
8009,
1883,
1011,
404,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
309,
16051,
7015,
13,
288,
203,
5411,
2991,
67,
1883,
18,
6206,
12,
12757,
1380,
12,
3576,
18,
15330,
16,
404,
10019,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import './IERC20.sol';
import './IERC721.sol';
import "./IERC721Receiver.sol";
import "./ERC165.sol";
import './Ownable.sol';
import './SafeMath.sol';
import './Address.sol';
import './Context.sol';
interface ILink is IERC20 {
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool success);
}
interface IApymonPack {
function depositErc20IntoEgg(
uint256 eggId,
address[] memory tokens,
uint256[] memory amounts
) external;
function depositErc721IntoEgg(
uint256 eggId,
address token,
uint256[] memory tokenIds
) external;
function isOpened(
uint256 eggId
) external view returns (bool);
}
interface IApymon {
function ownerOf(uint256 tokenId) external view returns (address);
}
interface ICryptoPunk {
function transferPunk(address to, uint punkIndex) external;
}
contract VRFRequestIDBase {
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
function makeRequestId(
bytes32 _keyHash,
uint256 _vRFInputSeed
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success);
function transferFrom(address from, address to, uint256 value) external returns (bool success);
}
abstract contract VRFConsumerBase is VRFRequestIDBase {
using SafeMath for uint256;
function fulfillRandomness(
bytes32 requestId,
uint256 randomness
) internal virtual;
function requestRandomness(
bytes32 _keyHash,
uint256 _fee,
uint256 _seed
) internal returns (bytes32 requestId) {
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, _seed));
uint256 vRFSeed = makeVRFInputSeed(_keyHash, _seed, address(this), nonces[_keyHash]);
nonces[_keyHash] = nonces[_keyHash].add(1);
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface immutable internal LINK;
address immutable private vrfCoordinator;
mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces;
constructor(
address _vrfCoordinator,
address _link
) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
function rawFulfillRandomness(
bytes32 requestId,
uint256 randomness
) external {
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
contract RandomNumberConsumer is VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
bool private progress = false;
uint256 private winner = 0;
address private distributer;
modifier onlyDistributer() {
require(distributer == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* Constructor inherits VRFConsumerBase
*
* Network: Kovan
* Chainlink VRF Coordinator address: 0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9
* LINK token address: 0xa36085F69e2889c224210F603D836748e7dC0088
* Key Hash: 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4
*/
constructor(address _distributer)
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
fee = 2 * 10 ** 18; // 2 LINK
distributer = _distributer;
}
/**
* Requests randomness from a user-provided seed
*/
function getRandomNumber(uint256 userProvidedSeed) public onlyDistributer returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
require(!progress, "now getting an random number.");
winner = 0;
progress = true;
return requestRandomness(keyHash, fee, userProvidedSeed);
}
/**
* Callback function used by VRF Coordinator
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
requestId = 0;
progress = false;
winner = randomness;
}
function getWinner() external view onlyDistributer returns (uint256) {
if(progress)
return 0;
return winner;
}
}
contract Distribution is ERC165, IERC721Receiver, Context, Ownable {
using SafeMath for uint256;
using Address for address;
RandomNumberConsumer public rnGenerator;
ICryptoPunk public _cryptoPunk = ICryptoPunk(0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB);
IApymonPack public _apymonPack = IApymonPack(0x3dFCB488F6e96654e827Ab2aB10a463B9927d4f9);
IApymonPack public _apymonPack721 = IApymonPack(0x74F9177825E3b0B7b242e0fEb03c38b3fF2dcB18);
IApymon public _apymon = IApymon(0x9C008A22D71B6182029b694B0311486e4C0e53DB);
address public wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public _randomCallCount = 0;
uint256 public _prevRandomCallCount = 0;
uint256 public _endIdForEthDistribution = 0;
// mapping eggId->punkId
mapping(uint256 => uint256) private _eggIdsOwnedPunk;
event WithdrawERC20(address indexed owner, address indexed token, uint256 amount);
event WithdrawERC721(address indexed owner, address indexed token, uint256 id);
event WithdrawPunk(address indexed owner, uint256 id);
constructor () {
rnGenerator = new RandomNumberConsumer(address(this));
}
function getRandomNumber() external onlyOwner {
rnGenerator.getRandomNumber(_randomCallCount);
_randomCallCount = _randomCallCount + 1;
}
function distributeFirstCryptoPunk() external onlyOwner {
require(_prevRandomCallCount != _randomCallCount, "Please generate random number.");
require(rnGenerator.getWinner() != 0, "Please wait until random number generated.");
_prevRandomCallCount = _randomCallCount;
uint256 eggId = rnGenerator.getWinner().mod(6000); // distribute first cryptoPunk to 0~5999
_eggIdsOwnedPunk[eggId] = 7207;
}
function distributeSecondCryptoPunk() external onlyOwner {
require(_prevRandomCallCount != _randomCallCount, "Please generate random number.");
require(rnGenerator.getWinner() != 0, "Please wait until random number generated.");
_prevRandomCallCount = _randomCallCount;
uint256 eggId = rnGenerator.getWinner().mod(400) + 6000; // distribute first cryptoPunk to 6000~6399
_eggIdsOwnedPunk[eggId] = 7006;
}
function withdrawPunk(uint256 eggId) external {
address eggOwner = _apymon.ownerOf(eggId);
require(eggOwner == msg.sender, "Invalid egg owner");
require(_apymonPack.isOpened(eggId), "Unopened egg");
uint256 punkId = _eggIdsOwnedPunk[eggId];
require(punkId > 0, "Invalid punk id");
_cryptoPunk.transferPunk(msg.sender, punkId);
_eggIdsOwnedPunk[eggId] = 0;
}
function checkPunk(uint256 eggId) external view returns(uint256 punkId) {
address eggOwner = _apymon.ownerOf(eggId);
require(eggOwner == msg.sender, "Invalid egg owner");
require(_apymonPack.isOpened(eggId), "Unopened egg");
punkId = _eggIdsOwnedPunk[eggId];
require(punkId > 0, "Invalid punk id");
}
function distributeERC20Token(address token, uint256 amount) external onlyOwner returns (uint256 eggId) {
require(token != address(0));
require(amount > 0, "Invalide erc20 amount to deposit");
require(_prevRandomCallCount != _randomCallCount, "Please generate random number.");
require(rnGenerator.getWinner() != 0, 'Please wait until random number generated.');
_prevRandomCallCount = _randomCallCount;
eggId = rnGenerator.getWinner().mod(6400);
address[] memory tokens = new address[](1);
uint256[] memory amounts = new uint256[](1);
tokens[0] = token;
amounts[0] = amount;
IERC20(token).approve(address(_apymonPack), amount);
_apymonPack.depositErc20IntoEgg(eggId, tokens, amounts);
}
function distributeERC721Token(address token, uint256 tokenId) external onlyOwner {
require(token != address(0));
require(_prevRandomCallCount != _randomCallCount, "Please generate random number.");
require(rnGenerator.getWinner() != 0, 'Please wait until random number generated.');
_prevRandomCallCount = _randomCallCount;
uint256 eggId = rnGenerator.getWinner().mod(6400);
uint256[] memory tokenIds = new uint256[](1);
tokenIds[0] = tokenId;
IERC721(token).approve(address(_apymonPack721), tokenId);
_apymonPack721.depositErc721IntoEgg(eggId, token, tokenIds);
}
function distributeApymonToken(uint256 tokenId) external onlyOwner {
require(_prevRandomCallCount != _randomCallCount, "Please generate random number.");
require(rnGenerator.getWinner() != 0, 'Please wait until random number generated.');
_prevRandomCallCount = _randomCallCount;
uint256 eggId = rnGenerator.getWinner().mod(6400);
if(eggId == tokenId) {
if(eggId >= 3200)
eggId = eggId - 1;
else
eggId = eggId + 1;
}
uint256[] memory tokenIds = new uint256[](1);
tokenIds[0] = tokenId;
IERC721(address(_apymon)).approve(address(_apymonPack721), tokenId);
_apymonPack721.depositErc721IntoEgg(eggId, address(_apymon), tokenIds);
}
function approveWethToPack() external {
IERC20(wethAddr).approve(address(_apymonPack), 100 ether);
}
function distributeWeth(uint256 startId, uint256 endId) external onlyOwner {
require((_endIdForEthDistribution == 0 && startId == 0) || (startId == _endIdForEthDistribution + 1), "startId is incorrect.");
require(endId >= startId && endId <= 6399, "endId is incorrect.");
_endIdForEthDistribution = endId;
address[] memory tokens = new address[](1);
uint256[] memory amounts = new uint256[](1);
tokens[0] = wethAddr;
for (uint256 i = startId; i <= endId; i++) {
if (i > 6395) { // 6396 ~ 6400
amounts[0] = 0.2 ether;
} else if (i > 6365) { // 6366 ~ 6395
amounts[0] = 0.1 ether;
} else if (i > 6300) { // 6301 ~ 6365
amounts[0] = 0.064 ether;
} else if (i > 6000) { // 6001 ~ 6300
amounts[0] = 0.032 ether;
} else if (i > 4000) { // 4001 ~ 6000
amounts[0] = 0.016 ether;
} else if (i > 500) { // 501 ~ 4000
amounts[0] = 0.008 ether;
} else {
amounts[0] = 0.004 ether; // 1 ~ 500
}
IApymonPack(_apymonPack).depositErc20IntoEgg(i, tokens, amounts);
}
}
function withdrawERC20ToOwner(address token) external onlyOwner {
uint256 amount = IERC20(token).balanceOf(address(this));
IERC20(token).transfer(owner(), amount);
emit WithdrawERC20(owner(), token, amount);
}
function withdrawERC721ToOwner(address token, uint256 id) external onlyOwner {
IERC721(token).safeTransferFrom(address(this), owner(), id);
emit WithdrawERC721(owner(), token, id);
}
function withdrawPunkToOwner(uint256 id) external onlyOwner {
_cryptoPunk.transferPunk(owner(), id);
emit WithdrawPunk(owner(), id);
}
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return this.onERC721Received.selector;
}
} | distribute first cryptoPunk to 0~5999
| uint256 eggId = rnGenerator.getWinner().mod(6000); | 5,741,060 | [
1,
2251,
887,
1122,
8170,
52,
1683,
358,
374,
98,
25,
11984,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
25144,
548,
273,
20594,
3908,
18,
588,
59,
7872,
7675,
1711,
12,
26,
3784,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "./interfaces/SnowflakeInterface.sol";
import "./interfaces/IdentityRegistryInterface.sol";
/**
* @title Ice Protocol
* @author Harsh Rajat
* @notice Create Protocol Less File Storage, Grouping, Hassle free Encryption / Decryption and Stamping using Snowflake
* @dev This Contract forms File Storage / Stamping / Encryption part of Hydro Protocols
*/
contract Ice {
/* ***************
* DEFINE ENUM
*************** */
enum NoticeType {info, warning, error}
enum GlobalItemProp {sharedTo, stampedTo}
/* ***************
* DEFINE VARIABLES
*************** */
/* for each file stored, ensure they can be retrieved publicly.
* associationIndex starts at 0 and will always increment
* given an associationIndex, any file can be retrieved.
*/
mapping (uint => mapping(uint => Association)) globalItems;
uint public globalIndex1; // store the first index of association to retrieve files
uint public globalIndex2; // store the first index of association to retrieve files
/* for each user (EIN), look up the Transitioon State they have
* stored on a given index.
*/
mapping (uint => AtomicityState) public atomicity;
/* for each user (EIN), look up the file they have
* stored on a given index.
*/
mapping (uint => mapping(uint => File)) files;
mapping (uint => mapping(uint => SortOrder)) public fileOrder; // Store round robin order of files
mapping (uint => uint) public fileCount; // store the maximum file count reached to provide looping functionality
/* for each user (EIN), look up the group they have
* stored on a given index. Default group 0 indicates
* root folder
*/
mapping (uint => mapping(uint => Group)) groups;
mapping (uint => mapping(uint => SortOrder)) public groupOrder; // Store round robin order of group
mapping (uint => uint) public groupCount; // store the maximum group count reached to provide looping functionality
/* for each user (EIN), look up the incoming transfer request
* stored on a given index.
*/
mapping (uint => mapping(uint => Association)) transfers;
mapping (uint => mapping(uint => SortOrder)) public transferOrder; // Store round robin order of transfers
mapping (uint => uint) public transferIndex; // store the maximum transfer request count reached to provide looping functionality
/* for each user (EIN), look up the incoming sharing files
* stored on a given index.
*/
mapping (uint => mapping(uint => GlobalRecord)) public shares;
mapping (uint => mapping(uint => SortOrder)) public shareOrder; // Store round robin order of sharing
mapping (uint => uint) public shareCount; // store the maximum shared items count reached to provide looping functionality
/* for each user (EIN), look up the incoming sharing files
* stored on a given index.
*/
mapping (uint => mapping(uint => GlobalRecord)) public stampings;
mapping (uint => mapping(uint => SortOrder)) public stampingOrder; // Store round robin order of stamping
mapping (uint => uint) public stampingCount; // store the maximum file index reached to provide looping functionality
/* for each user (EIN), look up the incoming sharing files
* stored on a given index.
*/
mapping (uint => mapping(uint => GlobalRecord)) public stampingsRequest;
mapping (uint => mapping(uint => SortOrder)) public stampingsRequestOrder; // Store round robin order of stamping requests
mapping (uint => uint) public stampingsRequestCount; // store the maximum file index reached to provide looping functionality
/* for each user (EIN), have a whitelist and blacklist
* association which can handle certain functions automatically.
*/
mapping (uint => mapping(uint => bool)) public whitelist;
mapping (uint => mapping(uint => bool)) public blacklist;
/* for referencing SnowFlake for Identity Registry (ERC-1484).
*/
SnowflakeInterface public snowflake;
IdentityRegistryInterface public identityRegistry;
/* ***************
* DEFINE STRUCTURES
*************** */
/* To define ownership info of a given Item.
*/
struct ItemOwner {
uint EIN; // the EIN of the owner
uint index; // the key at which the item is stored
}
/* To define global file association with EIN
* Combining EIN and itemIndex and properties will give access to
* item data.
*/
struct Association {
ItemOwner ownerInfo; // To Store Iteminfo
bool isFile; // whether the Item is File or Group
bool isHidden; // Whether the item is hidden or not
bool isStamped; // Whether the item is stamped atleast once
bool deleted; // whether the association is deleted
uint8 sharedToCount; // the count of sharing
uint8 stampedToCount; // the count of stamping
mapping (uint8 => ItemOwner) sharedTo; // to contain share to
mapping (uint8 => ItemOwner) stampedTo; // to have stamping reqs
}
struct GlobalRecord {
uint i1; // store associated global index 1 for access
uint i2; // store associated global index 2 for access
}
/* To define File structure of all stored files
*/
struct File {
// File Meta Data
GlobalRecord rec; // store the association in global record
uint fileOwner; // store file owner EIN
// File Properties
uint8 protocol; // store protocol of the file stored | 0 is URL, 1 is IPFS
bytes protocolMeta; // store metadata of the protocol
string name; // the name of the file
string hash; // store the hash of the file for verification | 0x000 for deleted files
bytes8 ext; // store the extension of the file
uint32 timestamp; // to store the timestamp of the block when file is created
// File Properties - Encryption Properties
bool encrypted; // whether the file is encrypted
mapping (address => string) encryptedHash; // Maps Individual address to the stored hash
// File Group Properties
uint associatedGroupIndex;
uint associatedGroupFileIndex;
// File Transfer Properties
mapping (uint => uint) transferHistory; // To maintain histroy of transfer of all EIN
uint transferCount; // To maintain the transfer count for mapping
uint transferEIN; // To record EIN of the user to whom trasnfer is inititated
uint transferIndex; // To record the transfer specific index of the transferee
bool markedForTransfer; // Mark the file as transferred
}
/* To connect Files in linear grouping,
* sort of like a folder, 0 or default grooupID is root
*/
struct Group {
GlobalRecord rec; // store the association in global record
string name; // the name of the Group
mapping (uint => SortOrder) groupFilesOrder; // the order of files in the current group
uint groupFilesCount; // To keep the count of group files
}
/* To define the order required to have double linked list
*/
struct SortOrder {
uint next; // the next ID of the order
uint prev; // the prev ID of the order
uint pointerID; // what it should point to in the mapping
bool active; // whether the node is active or not
}
/* To define state and flags for Individual things,
* used in cases where state change should be atomic
*/
struct AtomicityState {
bool lockFiles;
bool lockGroups;
bool lockTransfers;
bool lockSharings;
}
/* ***************
* DEFINE EVENTS
*************** */
// When File is created
event FileCreated(
uint EIN,
uint fileIndex,
string fileName
);
// When File is renamed
event FileRenamed(
uint EIN,
uint fileIndex,
string fileName
);
// When File is moved
event FileMoved(
uint EIN,
uint fileIndex,
uint groupIndex,
uint groupFileIndex
);
// When File is deleted
event FileDeleted(
uint EIN,
uint fileIndex
);
// When Group is created
event GroupCreated(
uint EIN,
uint groupIndex,
string groupName
);
// When Group is renamed
event GroupRenamed(
uint EIN,
uint groupIndex,
string groupName
);
// When Group Status is changed
event GroupDeleted(
uint EIN,
uint groupIndex,
uint groupReplacedIndex
);
// When Transfer is initiated from owner
event FileTransferInitiated(
uint indexed EIN,
uint indexed transfereeEIN,
uint indexed fileID
);
// When whitelist is updated
event AddedToWhitelist(
uint EIN,
uint recipientEIN
);
event RemovedFromWhitelist(
uint EIN,
uint recipientEIN
);
// When blacklist is updated
event AddedToBlacklist(
uint EIN,
uint recipientEIN
);
event RemovedFromBlacklist(
uint EIN,
uint recipientEIN
);
// Notice Events
event Notice(
uint indexed EIN,
string indexed notice,
uint indexed statusType
);
/* ***************
* DEFINE CONSTRUCTORS AND RELATED FUNCTIONS
*************** */
// CONSTRUCTOR / FUNCTIONS
address snowflakeAddress = 0xcF1877AC788a303cAcbbfE21b4E8AD08139f54FA; //0xB536a9b68e7c1D2Fd6b9851Af2F955099B3A59a9; // For local use
constructor (/*address snowflakeAddress*/) public {
snowflake = SnowflakeInterface(snowflakeAddress);
identityRegistry = IdentityRegistryInterface(snowflake.identityRegistryAddress());
}
/* ***************
* DEFINE CONTRACT FUNCTIONS
*************** */
// 1. GLOBAL ITEMS FUNCTIONS
/**
* @dev Function to get global items
* @param _index1 is the first index of item
* @param _index2 is the second index of item
*/
function getGlobalItems(uint _index1, uint _index2)
external view
returns (uint ownerEIN, uint itemRecord, bool isFile, bool isHidden, bool deleted, uint sharedToCount, uint stampingReqsCount) {
ownerEIN = globalItems[_index1][_index2].ownerInfo.EIN;
itemRecord = globalItems[_index1][_index2].ownerInfo.index;
isFile = globalItems[_index1][_index2].isFile;
isHidden = globalItems[_index1][_index2].isHidden;
deleted = globalItems[_index1][_index2].deleted;
sharedToCount = globalItems[_index1][_index2].sharedToCount;
stampingReqsCount = globalItems[_index1][_index2].stampedToCount;
}
/**
* @dev Function to get info of mapping to user for a specific global item
* @param _index1 is the first index of global item
* @param _index2 is the second index of global item
* @param _ofType indicates the type. 0 - shares, 1 - transferReqs
* @param _mappedIndex is the index
* @return mappedToEIN is the user (EIN)
* @return atIndex is the specific index in question
*/
function getGlobalItemsMapping(uint _index1, uint _index2, uint8 _ofType, uint8 _mappedIndex)
external view
returns (uint mappedToEIN, uint atIndex) {
ItemOwner memory _mappedItem;
// Allocalte based on type.
if (_ofType == uint8(GlobalItemProp.sharedTo)) {
_mappedItem = globalItems[_index1][_index2].sharedTo[_mappedIndex];
}
else if (_ofType == uint8(GlobalItemProp.stampedTo)) {
_mappedItem = globalItems[_index1][_index2].stampedTo[_mappedIndex];
}
mappedToEIN = _mappedItem.EIN;
atIndex = _mappedItem.index;
}
/**
* @dev Private Function to get global item via the record struct
* @param _rec is the GlobalRecord Struct
*/
function _getGlobalItemViaRecord(GlobalRecord memory _rec)
internal pure
returns (uint _i1, uint _i2) {
_i1 = _rec.i1;
_i2 = _rec.i2;
}
/**
* @dev Private Function to add item to global items
* @param _ownerEIN is the EIN of global items
* @param _itemIndex is the index at which the item exists on the user mapping
* @param _isFile indicates if the item is file or group
* @param _isHidden indicates if the item has is hiddden or not
*/
function _addItemToGlobalItems(uint _ownerEIN, uint _itemIndex, bool _isFile, bool _isHidden, bool _isStamped)
internal
returns (uint i1, uint i2){
// Increment global Item (0, 0 is always reserved | Is User Avatar)
globalIndex1 = globalIndex1;
globalIndex2 = globalIndex2 + 1;
if (globalIndex2 == 0) {
// This is loopback, Increment newIndex1
globalIndex1 = globalIndex1 + 1;
require (
globalIndex1 > 0,
"Storage Full"
);
}
// Add item to global item, no stiching it
globalItems[globalIndex1][globalIndex2] = Association (
ItemOwner (
_ownerEIN, // Owner EIN
_itemIndex // Item stored at what index for that EIN
),
_isFile, // Item is file or group
_isHidden, // whether stamping is initiated or not
_isStamped, // whether file is stamped or not
false, // Item is deleted or still exists
0, // the count of shared EINs
0 // the count of stamping requests
);
i1 = globalIndex1;
i2 = globalIndex2;
}
/**
* @dev Private Function to delete a global items
* @param _rec is the GlobalRecord Struct
*/
function _deleteGlobalRecord(GlobalRecord memory _rec)
internal {
globalItems[_rec.i1][_rec.i2].deleted = true;
}
function _getEINsForGlobalItemsMapping(mapping (uint8 => ItemOwner) storage _relatedMapping, uint8 _count)
internal view
returns (uint[32] memory EINs){
uint8 i = 0;
while (_count != 0) {
EINs[i] = _relatedMapping[_count].EIN;
_count--;
}
}
/**
* @dev Private Function to find the relevant mapping index of item mapped in non owner
* @param _relatedMapping is the passed pointer of relative mapping of global item Association
* @param _count is the count of relative mapping of global item Association
* @param _searchForEIN is the non-owner EIN to search
* @return mappedIndex is the index which is where the relative mapping points to for those items
*/
function _findGlobalItemsMapping(mapping (uint8 => ItemOwner) storage _relatedMapping, uint8 _count, uint256 _searchForEIN)
internal view
returns (uint8 mappedIndex) {
// Logic
mappedIndex = 0;
while (_count != 0) {
if (_relatedMapping[_count].EIN == _searchForEIN) {
mappedIndex = _count;
_count = 1;
}
_count--;
}
}
/**
* @dev Private Function to add to global items mapping
* @param _rec is the Global Record
* @param _ofType is the type of global item properties
* @param _mappedItem is the non-owner mapping of stored item
*/
function _addToGlobalItemsMapping(GlobalRecord storage _rec, uint8 _ofType, ItemOwner memory _mappedItem)
internal
returns (uint8 _newCount) {
// Logic
// Allocalte based on type.
if (_ofType == uint8(GlobalItemProp.sharedTo)) {
_newCount = globalItems[_rec.i1][_rec.i2].sharedToCount + 1;
globalItems[_rec.i1][_rec.i2].sharedTo[_newCount] = _mappedItem;
}
else if (_ofType == uint8(GlobalItemProp.stampedTo)) {
_newCount = globalItems[_rec.i1][_rec.i2].stampedToCount + 1;
globalItems[_rec.i1][_rec.i2].stampedTo[_newCount] = _mappedItem;
}
globalItems[_rec.i1][_rec.i2].stampedToCount = _newCount;
require (
(_newCount > globalItems[_rec.i1][_rec.i2].stampedToCount),
"Global Mapping Full"
);
}
/**
* @dev Private Function to remove from global items mapping
* @param _rec is the Global Record
* @param _mappedIndex is the non-owner mapping of stored item
*/
function _removeFromGlobalItemsMapping(GlobalRecord memory _rec, uint8 _mappedIndex)
internal
returns (uint8 _newCount) {
// Logic
// Just swap and deduct
_newCount = globalItems[_rec.i1][_rec.i2].sharedToCount;
globalItems[_rec.i1][_rec.i2].sharedTo[_mappedIndex] = globalItems[_rec.i1][_rec.i2].sharedTo[_newCount];
require (
(_newCount > 0),
"Invalid Global Mapping"
);
_newCount = _newCount - 1;
globalItems[_rec.i1][_rec.i2].sharedToCount = _newCount;
}
// 2. FILE FUNCTIONS
/**
* @dev Function to get all the files of an EIN
* @param _ein is the owner EIN
* @param _seedPointer is the seed of the order from which it should begin
* @param _limit is the limit of file indexes requested
* @param _asc is the order by which the files will be presented
*/
function getFileIndexes(uint _ein, uint _seedPointer, uint16 _limit, bool _asc)
external view
returns (uint[20] memory fileIndexes) {
fileIndexes = _getIndexes(fileOrder[_ein], _seedPointer, _limit, _asc);
}
/**
* @dev Function to get file info of an EIN
* @param _ein is the owner EIN
* @param _fileIndex is index of the file
*/
function getFile(uint _ein, uint _fileIndex)
external view
returns (uint8 protocol, bytes memory protocolMeta, string memory name, string memory hash, bytes8 ext, uint32 timestamp, bool encrypted, uint associatedGroupIndex, uint associatedGroupFileIndex) {
// Logic
protocol = files[_ein][_fileIndex].protocol;
protocolMeta = files[_ein][_fileIndex].protocolMeta;
name = files[_ein][_fileIndex].name;
hash = files[_ein][_fileIndex].hash;
ext = files[_ein][_fileIndex].ext;
timestamp = files[_ein][_fileIndex].timestamp;
encrypted = files[_ein][_fileIndex].encrypted;
associatedGroupIndex = files[_ein][_fileIndex].associatedGroupIndex;
associatedGroupFileIndex = files[_ein][_fileIndex].associatedGroupFileIndex;
}
/**
* @dev Function to get file tranfer info of an EIN
* @param _ein is the owner EIN
* @param _fileIndex is index of the file
*/
function getFileTransferInfo(uint _ein, uint _fileIndex)
external view
returns (uint transCount, uint transEIN, uint transIndex, bool forTrans) {
// Logic
transCount = files[_ein][_fileIndex].transferCount;
transEIN = files[_ein][_fileIndex].transferEIN;
transIndex = files[_ein][_fileIndex].transferIndex;
forTrans = files[_ein][_fileIndex].markedForTransfer;
}
/**
* @dev Function to get file tranfer owner info of an EIN
* @param _ein is the owner EIN
* @param _fileIndex is index of the file
* @param _transferIndex is index to poll
*/
function getFileTransferOwners(uint _ein, uint _fileIndex, uint _transferIndex)
external view
returns (uint recipientEIN) {
recipientEIN = files[_ein][_fileIndex].transferHistory[_transferIndex];
}
/**
* @dev Function to add File
* @param _protocol is the protocol used
* @param _protocolMeta is the metadata used by the protocol if any
* @param _name is the name of the file
* @param _hash is the hash of the stored file
* @param _ext is the extension of the file
* @param _encrypted defines if the file is encrypted or not
* @param _encryptedHash defines the encrypted public key password for the sender address
* @param _groupIndex defines the index of the group of file
*/
function addFile(uint8 _protocol, bytes memory _protocolMeta, string memory _name, string memory _hash, bytes8 _ext, bool _encrypted, string memory _encryptedHash, uint _groupIndex)
public {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check constraints
_isValidItem(_groupIndex, groupCount[ein]);
_isFilesOpLocked(ein);
_isGrpsOpLocked(ein);
// Set File & Group Atomicity
atomicity[ein].lockFiles = true;
atomicity[ein].lockGroups = true;
// Add to Global Items
uint index1;
uint index2;
(index1, index2) = _addItemToGlobalItems(ein, (fileCount[ein] + 1), true, false, false);
// Add file to group
groups[ein][_groupIndex].groupFilesCount = _addFileToGroup(ein, _groupIndex, (fileCount[ein] + 1));
// Finally create the file it to User (EIN)
files[ein][(fileCount[ein] + 1)] = File (
GlobalRecord(
index1, // Global Index 1
index2 // Global Index 2
),
ein, // File Owner
_protocol, // Protocol For Interpretation
_protocolMeta, // Serialized Hex of Array
_name, // Name of File
_hash, // Hash of File
_ext, // Extension of File
uint32(now), // Timestamp of File
_encrypted, // File Encyption
_groupIndex, // Store the group index
groups[ein][_groupIndex].groupFilesCount, // Store the group specific file index
1, // Transfer Count, treat creation as a transfer count
0, // Transfer EIN
0, // Transfer Index for Transferee
false // File is not flagged for Transfer
);
// To map encrypted password
files[ein][(fileCount[ein] + 1)].encryptedHash[msg.sender] = _encryptedHash;
// To map transfer history
files[ein][(fileCount[ein] + 1)].transferHistory[0] = ein;
// Add to Stitch Order & Increment index
fileCount[ein] = _addToSortOrder(fileOrder[ein], fileCount[ein], 0);
// Trigger Event
emit FileCreated(ein, (fileCount[ein] + 1), _name);
// Reset Files & Group Atomicity
atomicity[ein].lockFiles = false;
atomicity[ein].lockGroups = false;
}
/**
* @dev Function to change File Name
* @param _fileIndex is the index where file is stored
* @param _name is the name of stored file
*/
function changeFileName(uint _fileIndex, string calldata _name)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Logic
files[ein][_fileIndex].name = _name;
// Trigger Event
emit FileRenamed(ein, _fileIndex, _name);
}
/**
* @dev Function to move file to another group
* @param _fileIndex is the index where file is stored
* @param _newGroupIndex is the index of the new group where file has to be moved
*/
function moveFileToGroup(uint _fileIndex, uint _newGroupIndex)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isValidGrpOrder(ein, _newGroupIndex); // Check if the new group is valid
_isUnstampedItem(files[ein][_fileIndex].rec); // Check if the file is unstamped, can't move a stamped file
_isUnstampedItem(groups[ein][files[ein][_fileIndex].associatedGroupIndex].rec); // Check if the current group is unstamped, can't move a file from stamped group
_isUnstampedItem(groups[ein][_newGroupIndex].rec); // Check if the new group is unstamped, can't move a file from stamped group
_isFilesOpLocked(ein); // Check if the files operations are not locked for the user
_isGrpsOpLocked(ein); // Check if the groups operations are not locked for the user
// Set Files & Group Atomicity
atomicity[ein].lockFiles = true;
atomicity[ein].lockGroups = true;
uint GFIndex = _remapFileToGroup(ein, files[ein][_fileIndex].associatedGroupIndex, files[ein][_fileIndex].associatedGroupFileIndex, _newGroupIndex);
// Trigger Event
emit FileMoved(ein, _fileIndex, _newGroupIndex, GFIndex);
// Reset Files & Group Atomicity
atomicity[ein].lockFiles = false;
atomicity[ein].lockGroups = false;
}
/**
* @dev Function to delete file of the owner
* @param _fileIndex is the index where file is stored
*/
function deleteFile(uint _fileIndex)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isUnstampedItem(files[ein][_fileIndex].rec); // Check if the file is unstamped, can't delete a stamped file
// Set Files & Group Atomicity
atomicity[ein].lockFiles = true;
atomicity[ein].lockGroups = true;
_deleteFileAnyOwner(ein, _fileIndex);
// Reset Files & Group Atomicity
atomicity[ein].lockFiles = false;
atomicity[ein].lockGroups = false;
}
/**
* @dev Function to delete file of any EIN
* @param _ein is the owner EIN
* @param _fileIndex is the index where file is stored
*/
function _deleteFileAnyOwner(uint _ein, uint _fileIndex)
internal {
// Check Restrictions
_isValidItem(_fileIndex, fileCount[_ein]);
_isValidGrpOrder(_ein, files[_ein][_fileIndex].associatedGroupIndex);
// Get current Index, Stich check previous index so not required to recheck
uint currentIndex = fileCount[_ein];
// Remove item from sharing of other users
_removeAllShares(files[_ein][_fileIndex].rec);
// Deactivate From Global Items
_deleteGlobalRecord(files[_ein][_fileIndex].rec);
// Remove from Group which holds the File
_removeFileFromGroup(_ein, files[_ein][_fileIndex].associatedGroupIndex, files[_ein][_fileIndex].associatedGroupFileIndex);
// Swap File
files[_ein][_fileIndex] = files[_ein][currentIndex];
fileCount[_ein] = _stichSortOrder(fileOrder[_ein], _fileIndex, currentIndex, 0);
// Delete the latest group now
delete (files[_ein][currentIndex]);
// Trigger Event
emit FileDeleted(_ein, _fileIndex);
}
/**
* @dev Private Function to add file to a group
* @param _ein is the EIN of the intended user
* @param _groupIndex is the index of the group belonging to that user, 0 is reserved for root
* @param _fileIndex is the index of the file belonging to that user
*/
function _addFileToGroup(uint _ein, uint _groupIndex, uint _fileIndex)
internal
returns (uint) {
// Add File to a group is just adding the index of that file
uint currentIndex = groups[_ein][_groupIndex].groupFilesCount;
groups[_ein][_groupIndex].groupFilesCount = _addToSortOrder(groups[_ein][_groupIndex].groupFilesOrder, currentIndex, _fileIndex);
// Map group index and group order index in file
files[_ein][_fileIndex].associatedGroupIndex = _groupIndex;
files[_ein][_fileIndex].associatedGroupFileIndex = groups[_ein][_groupIndex].groupFilesCount;
return groups[_ein][_groupIndex].groupFilesCount;
}
/**
* @dev Private Function to remove file from a group
* @param _ein is the EIN of the intended user
* @param _groupIndex is the index of the group belonging to that user
* @param _groupFileOrderIndex is the index of the file order within that group
*/
function _removeFileFromGroup(uint _ein, uint _groupIndex, uint _groupFileOrderIndex)
internal {
uint maxIndex = groups[_ein][_groupIndex].groupFilesCount;
uint pointerID = groups[_ein][_groupIndex].groupFilesOrder[maxIndex].pointerID;
groups[_ein][_groupIndex].groupFilesCount = _stichSortOrder(groups[_ein][_groupIndex].groupFilesOrder, _groupFileOrderIndex, maxIndex, pointerID);
}
/**
* @dev Private Function to remap file from one group to another
* @param _ein is the EIN of the intended user
* @param _groupIndex is the index of the group belonging to that user, 0 is reserved for root
* @param _groupFileOrderIndex is the index of the file order within that group
* @param _newGroupIndex is the index of the new group belonging to that user
*/
function _remapFileToGroup(uint _ein, uint _groupIndex, uint _groupFileOrderIndex, uint _newGroupIndex)
internal
returns (uint) {
// Get file index for the Association
uint fileIndex = groups[_ein][_groupIndex].groupFilesOrder[_groupFileOrderIndex].pointerID;
// Remove File from existing group
_removeFileFromGroup(_ein, _groupIndex, _groupFileOrderIndex);
// Add File to new group
return _addFileToGroup(_ein, _newGroupIndex, fileIndex);
}
// 4. GROUP FILES FUNCTIONS
/**
* @dev Function to get all the files of an EIN associated with a group
* @param _ein is the owner EIN
* @param _groupIndex is the index where group is stored
* @param _seedPointer is the seed of the order from which it should begin
* @param _limit is the limit of file indexes requested
* @param _asc is the order by which the files will be presented
*/
function getGroupFileIndexes(uint _ein, uint _groupIndex, uint _seedPointer, uint16 _limit, bool _asc)
external view
returns (uint[20] memory groupFileIndexes) {
return _getIndexes(groups[_ein][_groupIndex].groupFilesOrder, _seedPointer, _limit, _asc);
}
// 4. GROUP FUNCTIONS
/**
* @dev Function to return group info for an EIN
* @param _ein the EIN of the user
* @param _groupIndex the index of the group
* @return index is the index of the group
* @return name is the name associated with the group
*/
function getGroup(uint _ein, uint _groupIndex)
external view
returns (uint index, string memory name) {
// Check constraints
_isValidItem(_groupIndex, groupCount[_ein]);
// Logic flow
index = _groupIndex;
if (_groupIndex == 0) {
name = "Root";
}
else {
name = groups[_ein][_groupIndex].name;
}
}
/**
* @dev Function to return group indexes used to retrieve info about group
* @param _ein the EIN of the user
* @param _seedPointer is the pointer (index) of the order mapping
* @param _limit is the number of indexes to return, capped at 20
* @param _asc is the order of group indexes in Ascending or Descending order
* @return groupIndexes the indexes of the groups associated with the ein in the preferred order
*/
function getGroupIndexes(uint _ein, uint _seedPointer, uint16 _limit, bool _asc)
external view
returns (uint[20] memory groupIndexes) {
groupIndexes = _getIndexes(groupOrder[_ein], _seedPointer, _limit, _asc);
}
/**
* @dev Create a new Group for the user
* @param _groupName describes the name of the group
*/
function createGroup(string memory _groupName)
public {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isGrpsOpLocked(ein);
// Set Group Atomicity
atomicity[ein].lockGroups = true;
// Check if this is unitialized, if so, initialize it, reserved value of 0 is skipped as that's root
uint currentGroupIndex = groupCount[ein];
uint nextGroupIndex = currentGroupIndex + 1;
// Add to Global Items
uint index1;
uint index2;
(index1, index2) = _addItemToGlobalItems(ein, nextGroupIndex, false, false, false);
// Assign it to User (EIN)
groups[ein][nextGroupIndex] = Group(
GlobalRecord(
index1, // Global Index 1
index2 // Global Index 2
),
_groupName, //name of Group
0 // The group file count
);
// Add to Stitch Order & Increment index
groupCount[ein] = _addToSortOrder(groupOrder[ein], currentGroupIndex, 0);
// Trigger Event
emit GroupCreated(ein, nextGroupIndex, _groupName);
// Reset Group Atomicity
atomicity[ein].lockGroups = false;
}
/**
* @dev Rename an existing Group for the user / ein
* @param _groupIndex describes the associated index of the group for the user / ein
* @param _groupName describes the new name of the group
*/
function renameGroup(uint _groupIndex, string calldata _groupName)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isNonReservedItem(_groupIndex);
_isValidItem(_groupIndex, groupCount[ein]);
// Replace the group name
groups[ein][_groupIndex].name = _groupName;
// Trigger Event
emit GroupRenamed(ein, _groupIndex, _groupName);
}
/**
* @dev Delete an existing group for the user / ein
* @param _groupIndex describes the associated index of the group for the user / ein
*/
function deleteGroup(uint _groupIndex)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isGroupFileFree(ein, _groupIndex); // Check that Group contains no Files
_isNonReservedItem(_groupIndex);
_isValidItem(_groupIndex, groupCount[ein]);
_isGrpsOpLocked(ein);
// Set Group Atomicity
atomicity[ein].lockGroups = true;
// Check if the group exists or not
uint currentGroupIndex = groupCount[ein];
// Remove item from sharing of other users
_removeAllShares(groups[ein][_groupIndex].rec);
// Deactivate from global record
_deleteGlobalRecord(groups[ein][_groupIndex].rec);
// Swap Index mapping & remap the latest group ID if this is not the last group
groups[ein][_groupIndex] = groups[ein][currentGroupIndex];
groupCount[ein] = _stichSortOrder(groupOrder[ein], _groupIndex, currentGroupIndex, 0);
// Delete the latest group now
delete (groups[ein][currentGroupIndex]);
// Trigger Event
emit GroupDeleted(ein, _groupIndex, currentGroupIndex);
// Reset Group Atomicity
atomicity[ein].lockGroups = false;
}
// 5. SHARING FUNCTIONS
/**
* @dev Function to share an item to other users, always called by owner of the Item
* @param _toEINs are the array of EINs which the item should be shared to
* @param _itemIndex is the index of the item to be shared to
* @param _isFile indicates if the item is file or group
*/
function shareItemToEINs(uint[] calldata _toEINs, uint _itemIndex, bool _isFile)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restriction
_isSharingsOpLocked(ein); // Check if sharing operations are locked or not for the owner
// Logic
// Set Lock
atomicity[ein].lockSharings = true;
// Warn: Unbounded Loop
for (uint i=0; i < _toEINs.length; i++) {
// call share for each EIN you want to share with
// Since its multiple share, don't put require blacklist but ignore the share
// if owner of the file is in blacklist
if (blacklist[_toEINs[i]][ein] == false) {
_shareItemToEIN(ein, _toEINs[i], _itemIndex, _isFile);
}
}
// Reset Lock
atomicity[ein].lockSharings = false;
}
/**
* @dev Function to remove a shared item from the multiple user's mapping, always called by owner of the Item
* @param _toEINs are the EINs to which the item should be removed from sharing
* @param _itemIndex is the index of the item on the owner's mapping
* @param _isFile indicates if the item is file or group
*/
function removeShareFromEINs(uint[32] memory _toEINs, uint _itemIndex, bool _isFile)
public {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restriction
_isSharingsOpLocked(ein); // Check if sharing operations are locked or not for the owner
// Logic
// Set Lock
atomicity[ein].lockSharings = true;
// Get reference of global item record
GlobalRecord memory rec;
if (_isFile == true) {
// is file
rec = files[ein][_itemIndex].rec;
}
else {
// is group
rec = groups[ein][_itemIndex].rec;
}
// Adjust for valid loop
uint count = globalItems[rec.i1][rec.i2].sharedToCount;
for (uint i=0; i < count; i++) {
// call share for each EIN you want to remove the share with
_removeShareFromEIN(_toEINs[i], rec, globalItems[rec.i1][rec.i2]);
}
// Reset Lock
atomicity[ein].lockSharings = false;
}
/**
* @dev Function to remove shared item by the non owner of that item
* @param _itemIndex is the index of the item in shares
*/
function removeSharingItemNonOwner(uint _itemIndex)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Logic
GlobalRecord memory rec = shares[ein][_itemIndex];
_removeShareFromEIN(ein, shares[ein][_itemIndex], globalItems[rec.i1][rec.i2]); // Handles atomicity and other Restrictions
}
/**
* @dev Private Function to share an item to Individual user
* @param _ein is the EIN to of the owner
* @param _toEIN is the EIN to which the item should be shared to
* @param _itemIndex is the index of the item to be shared to
* @param _isFile indicates if the item is file or group
*/
function _shareItemToEIN(uint _ein, uint _toEIN, uint _itemIndex, bool _isFile)
internal {
// Check Restrictions
_isNonOwner(_toEIN); // Recipient EIN should not be the owner
// Logic
// Set Lock
atomicity[_toEIN].lockSharings = true;
// Create Sharing
uint curIndex = shareCount[_toEIN];
uint nextIndex = curIndex + 1;
// no need to require as share can be multiple
// and thus should not hamper other sharings
if (nextIndex > curIndex) {
if (_isFile == true) {
// is file
shares[_toEIN][nextIndex] = files[_ein][_itemIndex].rec;
}
else {
// is group
shares[_toEIN][nextIndex] = groups[_ein][_itemIndex].rec;
}
// Add to share order & global mapping
shareCount[_toEIN] = _addToSortOrder(shareOrder[_toEIN], curIndex, 0);
_addToGlobalItemsMapping(shares[_toEIN][nextIndex], uint8(GlobalItemProp.sharedTo), ItemOwner(_toEIN, nextIndex));
}
// Reset Lock
atomicity[_toEIN].lockSharings = false;
}
/**
* @dev Private Function to remove a shared item from the user's mapping
* @param _toEIN is the EIN to which the item should be removed from sharing
* @param _rec is the global record of the file
* @param _globalItem is the pointer to the global item
*/
function _removeShareFromEIN(uint _toEIN, GlobalRecord memory _rec, Association storage _globalItem)
internal {
// Check Restrictions
_isNonOwner(_toEIN); // Recipient EIN should not be the owner
// Logic
// Set Lock
atomicity[_toEIN].lockSharings = true;
// Create Sharing
uint curIndex = shareCount[_toEIN];
// no need to require as share can be multiple
// and thus should not hamper other sharings removals
if (curIndex > 0) {
uint8 mappedIndex = _findGlobalItemsMapping(_globalItem.sharedTo, _globalItem.sharedToCount, _toEIN);
// Only proceed if mapping if found
if (mappedIndex > 0) {
uint _itemIndex = _globalItem.sharedTo[mappedIndex].index;
// Remove the share from global items mapping
_removeFromGlobalItemsMapping(_rec, mappedIndex);
// Swap the shares, then Reove from share order & stich
shares[_toEIN][_itemIndex] = shares[_toEIN][curIndex];
shareCount[_toEIN] = _stichSortOrder(shareOrder[_toEIN], _itemIndex, curIndex, 0);
}
}
// Reset Lock
atomicity[_toEIN].lockSharings = false;
}
/**
* @dev Function to remove all shares of an Item, always called by owner of the Item
* @param _rec is the global item record index
*/
function _removeAllShares(GlobalRecord memory _rec)
internal {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restriction
_isSharingsOpLocked(ein); // Check if sharing operations are locked or not for the owner
// Logic
// get and pass all EINs, remove share takes care of locking
uint[32] memory eins = _getEINsForGlobalItemsMapping(globalItems[_rec.i1][_rec.i2].sharedTo, globalItems[_rec.i1][_rec.i2].sharedToCount);
removeShareFromEINs(eins, globalItems[_rec.i1][_rec.i2].ownerInfo.index, globalItems[_rec.i1][_rec.i2].isFile);
// just adjust share count
globalItems[_rec.i1][_rec.i2].sharedToCount = 0;
}
// 6. STAMPING FUNCTIONS
// 8. WHITELIST / BLACKLIST FUNCTIONS
/**
* @dev Add a non-owner user to whitelist
* @param _nonOwnerEIN is the ein of the recipient
*/
function addToWhitelist(uint _nonOwnerEIN)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isNotBlacklist(ein, _nonOwnerEIN);
// Logic
whitelist[ein][_nonOwnerEIN] = true;
// Trigger Event
emit AddedToWhitelist(ein, _nonOwnerEIN);
}
/**
* @dev Remove a non-owner user from whitelist
* @param _nonOwnerEIN is the ein of the recipient
*/
function removeFromWhitelist(uint _nonOwnerEIN)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isNotBlacklist(ein, _nonOwnerEIN);
// Logic
whitelist[ein][_nonOwnerEIN] = false;
// Trigger Event
emit RemovedFromWhitelist(ein, _nonOwnerEIN);
}
/**
* @dev Remove a non-owner user to blacklist
* @param _nonOwnerEIN is the ein of the recipient
*/
function addToBlacklist(uint _nonOwnerEIN)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isNotWhitelist(ein, _nonOwnerEIN);
// Logic
blacklist[ein][_nonOwnerEIN] = true;
// Trigger Event
emit AddedToBlacklist(ein, _nonOwnerEIN);
}
/**
* @dev Remove a non-owner user from blacklist
* @param _nonOwnerEIN is the ein of the recipient
*/
function removeFromBlacklist(uint _nonOwnerEIN)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isNotWhitelist(ein, _nonOwnerEIN);
// Logic
whitelist[ein][_nonOwnerEIN] = false;
// Trigger Event
emit RemovedFromBlacklist(ein, _nonOwnerEIN);
}
// *. REFERENTIAL INDEXES FUNCTIONS
/**
* @dev Private Function to return maximum 20 Indexes of Files, Groups, Transfers,
* etc based on their SortOrder. 0 is always reserved but will point to Root in Group & Avatar in Files
* @param _orderMapping is the relevant sort order of Files, Groups, Transfers, etc
* @param _seedPointer is the pointer (index) of the order mapping
* @param _limit is the number of files requested | Maximum of 20 can be retrieved
* @param _asc is the order, i.e. Ascending or Descending
*/
function _getIndexes(mapping(uint => SortOrder) storage _orderMapping, uint _seedPointer, uint16 _limit, bool _asc)
internal view
returns (uint[20] memory sortedIndexes) {
uint next;
uint prev;
uint pointerID;
bool active;
// Get initial Order
(prev, next, pointerID, active) = _getOrder(_orderMapping, _seedPointer);
// Get Previous or Next Order | Round Robin Fashion
if (_asc == true) {
// Ascending Order
(prev, next, pointerID, active) = _getOrder(_orderMapping, next);
}
else {
// Descending Order
(prev, next, pointerID, active) = _getOrder(_orderMapping, prev);
}
uint16 i = 0;
if (_limit >= 20) {
_limit = 20; // always account for root
}
while (_limit != 0) {
if (active == false || pointerID == 0) {
_limit = 0;
if (pointerID == 0) {
//add root as Special case
sortedIndexes[i] = 0;
}
}
else {
// Get PointerID
sortedIndexes[i] = pointerID;
// Get Previous or Next Order | Round Robin Fashion
if (_asc == true) {
// Ascending Order
(prev, next, pointerID, active) = _getOrder(_orderMapping, next);
}
else {
// Descending Order
(prev, next, pointerID, active) = _getOrder(_orderMapping, prev);
}
// Increment counter
i++;
// Decrease Limit
_limit--;
}
}
}
// *. DOUBLE LINKED LIST (ROUND ROBIN) FOR OPTIMIZATION FUNCTIONS / DELETE / ADD / ETC
/**
* @dev Private Function to facilitate returning of double linked list used
* @param _orderMapping is the relevant sort order of Files, Groups, Transfers, etc
* @param _seedPointer is the pointer (index) of the order mapping
*/
function _getOrder(mapping(uint => SortOrder) storage _orderMapping, uint _seedPointer)
internal view
returns (uint prev, uint next, uint pointerID, bool active) {
prev = _orderMapping[_seedPointer].prev;
next = _orderMapping[_seedPointer].next;
pointerID = _orderMapping[_seedPointer].pointerID;
active = _orderMapping[_seedPointer].active;
}
/**
* @dev Private Function to facilitate adding of double linked list used to preserve order and form cicular linked list
* @param _orderMapping is the relevant sort order of Files, Groups, Transfers, etc
* @param _currentIndex is the index which will be maximum
* @param _pointerID is the ID to which it should point to, pass 0 to calculate on existing logic flow
*/
function _addToSortOrder(mapping(uint => SortOrder) storage _orderMapping, uint _currentIndex, uint _pointerID)
internal
returns (uint) {
// Next Index is always +1
uint nextIndex = _currentIndex + 1;
require (
(nextIndex > _currentIndex || _pointerID != 0),
"Slots Full"
);
// Assign current order to next pointer
_orderMapping[_currentIndex].next = nextIndex;
_orderMapping[_currentIndex].active = true;
// Special case of root of sort order
if (_currentIndex == 0) {
_orderMapping[0].next = nextIndex;
}
// Assign initial group prev order
_orderMapping[0].prev = nextIndex;
// Whether This is assigned or calculated
uint pointerID;
if (_pointerID == 0) {
pointerID = nextIndex;
}
else {
pointerID = _pointerID;
}
// Assign next group order pointer and prev pointer
_orderMapping[nextIndex] = SortOrder(
0, // next index
_currentIndex, // prev index
pointerID, // pointerID
true // mark as active
);
return nextIndex;
}
/**
* @dev Private Function to facilitate stiching of double linked list used to preserve order with delete
* @param _orderMapping is the relevant sort order of Files, Groups, Transfer, etc
* @param _remappedIndex is the index which is swapped to from the latest index
* @param _maxIndex is the index which will always be maximum
* @param _pointerID is the ID to which it should point to, pass 0 to calculate on existing logic flow
*/
function _stichSortOrder(mapping(uint => SortOrder) storage _orderMapping, uint _remappedIndex, uint _maxIndex, uint _pointerID)
internal
returns (uint){
// Stich Order
uint prevGroupIndex = _orderMapping[_remappedIndex].prev;
uint nextGroupIndex = _orderMapping[_remappedIndex].next;
_orderMapping[prevGroupIndex].next = nextGroupIndex;
_orderMapping[nextGroupIndex].prev = prevGroupIndex;
// Check if this is not the top order number
if (_remappedIndex != _maxIndex) {
// Change order mapping and remap
_orderMapping[_remappedIndex] = _orderMapping[_maxIndex];
if (_pointerID == 0) {
_orderMapping[_remappedIndex].pointerID = _remappedIndex;
}
else {
_orderMapping[_remappedIndex].pointerID = _pointerID;
}
_orderMapping[_orderMapping[_remappedIndex].next].prev = _remappedIndex;
_orderMapping[_orderMapping[_remappedIndex].prev].next = _remappedIndex;
}
// Turn off the non-stich group
_orderMapping[_maxIndex].active = false;
// Decrement count index if it's non-zero
require (
(_maxIndex > 0),
"Item Not Found"
);
// return new index
return _maxIndex - 1;
}
// *. GENERAL CONTRACT HELPERS
/** @dev Private Function to append two strings together
* @param a the first string
* @param b the second string
*/
function _append(string memory a, string memory b)
internal pure
returns (string memory) {
return string(abi.encodePacked(a, b));
}
/* ***************
* DEFINE MODIFIERS AS INTERNAL VIEW FUNTIONS
*************** */
/**
* @dev Private Function to check that only owner can have access
* @param _ein The EIN of the file Owner
*/
function _isOwner(uint _ein)
internal view {
require (
(identityRegistry.getEIN(msg.sender) == _ein),
"Only Owner"
);
}
/**
* @dev Private Function to check that only non-owner can have access
* @param _ein The EIN of the file Owner
*/
function _isNonOwner(uint _ein)
internal view {
require (
(identityRegistry.getEIN(msg.sender) != _ein),
"Only Non-Owner"
);
}
/**
* @dev Private Function to check that only owner of EIN can access this
* @param _ownerEIN The EIN of the file Owner
* @param _fileIndex The index of the file
*/
function _isFileOwner(uint _ownerEIN, uint _fileIndex)
internal view {
require (
(identityRegistry.getEIN(msg.sender) == files[_ownerEIN][_fileIndex].fileOwner),
"Only File Owner"
);
}
/**
* @dev Private Function to check that only non-owner of EIN can access this
* @param _ownerEIN The EIN of the file Owner
* @param _fileIndex The index of the file
*/
function _isFileNonOwner(uint _ownerEIN, uint _fileIndex)
internal view {
require (
(identityRegistry.getEIN(msg.sender) != files[_ownerEIN][_fileIndex].fileOwner),
"Only File Non-Owner"
);
}
/**
* @dev Private Function to check that only valid EINs can have access
* @param _ein The EIN of the Passer
*/
function _isValidEIN(uint _ein)
internal view {
require (
(identityRegistry.identityExists(_ein) == true),
"EIN not Found"
);
}
/**
* @dev Private Function to check that only unique EINs can have access
* @param _ein1 The First EIN
* @param _ein2 The Second EIN
*/
function _isUnqEIN(uint _ein1, uint _ein2)
internal pure {
require (
(_ein1 != _ein2),
"Same EINs"
);
}
/**
* @dev Private Function to check that a file exists for the current EIN
* @param _fileIndex The index of the file
*/
function _doesFileExists(uint _fileIndex)
internal view {
require (
(_fileIndex <= fileCount[identityRegistry.getEIN(msg.sender)]),
"File not Found"
);
}
/**
* @dev Private Function to check that a file has been marked for transferee EIN
* @param _fileIndex The index of the file
*/
function _isMarkedForTransferee(uint _fileOwnerEIN, uint _fileIndex, uint _transfereeEIN)
internal view {
// Check if the group file exists or not
require (
(files[_fileOwnerEIN][_fileIndex].transferEIN == _transfereeEIN),
"File not marked for Transfers"
);
}
/**
* @dev Private Function to check that a file hasn't been marked for stamping
* @param _rec is struct record containing global association
*/
function _isUnstampedItem(GlobalRecord memory _rec)
internal view {
// Check if the group file exists or not
require (
(globalItems[_rec.i1][_rec.i2].isStamped == false),
"Item Stamped"
);
}
/**
* @dev Private Function to check that Rooot ID = 0 is not modified as this is root
* @param _index The index to check
*/
function _isNonReservedItem(uint _index)
internal pure {
require (
(_index > 0),
"Reserved Item"
);
}
/**
* @dev Private Function to check that Group Order is valid
* @param _ein is the EIN of the target user
* @param _groupIndex The index of the group order
*/
function _isGroupFileFree(uint _ein, uint _groupIndex)
internal view {
require (
(groups[_ein][_groupIndex].groupFilesCount == 0),
"Group has Files"
);
}
/**
* @dev Private Function to check if an item exists
* @param _itemIndex the index of the item
* @param _itemCount is the count of that mapping
*/
function _isValidItem(uint _itemIndex, uint _itemCount)
internal pure {
require (
(_itemIndex <= _itemCount),
"Item Not Found"
);
}
/**
* @dev Private Function to check that Group Order is valid
* @param _ein is the EIN of the target user
* @param _groupOrderIndex The index of the group order
*/
function _isValidGrpOrder(uint _ein, uint _groupOrderIndex)
internal view {
require (
(_groupOrderIndex == 0 || groupOrder[_ein][_groupOrderIndex].active == true),
"Group Order not Found"
);
}
/**
* @dev Private Function to check that operation of Files is currently locked or not
* @param _ein is the EIN of the target user
*/
function _isFilesOpLocked(uint _ein)
internal view {
require (
(atomicity[_ein].lockFiles == false),
"Files Locked"
);
}
/**
* @dev Private Function to check that operation of Groups is currently locked or not
* @param _ein is the EIN of the target user
*/
function _isGrpsOpLocked(uint _ein)
internal view {
require (
(atomicity[_ein].lockGroups == false),
"Groups Locked"
);
}
/**
* @dev Private Function to check that operation of Sharings is currently locked or not
* @param _ein is the EIN of the target user
*/
function _isSharingsOpLocked(uint _ein)
internal view {
require (
(atomicity[_ein].lockSharings == false),
"Sharing Locked"
);
}
/**
* @dev Private Function to check that operation of Transfers is currently locked or not
* @param _ein is the EIN of the target user
*/
function _isTransfersOpLocked(uint _ein)
internal view {
require (
(atomicity[_ein].lockTransfers == false),
"Transfers Locked"
);
}
/**
* @dev Private Function to check if the user is not blacklisted by the current user
* @param _ein is the EIN of the self
* @param _otherEIN is the EIN of the target user
*/
function _isNotBlacklist(uint _ein, uint _otherEIN)
internal view {
require (
(blacklist[_ein][_otherEIN] == false),
"EIN Blacklisted"
);
}
/**
* @dev Private Function to check if the user is not whitelisted by the current user
* @param _ein is the EIN of the self
* @param _otherEIN is the EIN of the target user
*/
function _isNotWhitelist(uint _ein, uint _otherEIN)
internal view {
require (
(whitelist[_ein][_otherEIN] == false),
"EIN Whitelisted"
);
}
// *. FOR DEBUGGING CONTRACT
// To Build Groups & File System for users
function debugBuildFS()
public {
// Create Groups
createGroup("A.Images");
createGroup("B.Movies");
createGroup("C.Crypto");
createGroup("D.Others");
createGroup("E.AdobeContract");
// Create Files
// addFile(protocol, protocolMeta, name, _hash, ext, encrypted, encryptedHash, groupIndex)
addFile(1, "0x00", "index", "QmTecWfmvvsPdZXuYrLgCTqRj9YgBiAUL4ZCr9iwDnp9q7", "0x123", false, "", 0);
addFile(1, "0x00", "family", "QmTecWfmvvsPdZXuYrLgCTqRj9YgBiAUL4ZCr9iwDnp9q7", "0x123", false, "", 0);
addFile(1, "0x00", "myportrait", "QmTecWfmvvsPdZXuYrLgCTqRj9YgBiAUL4ZCr9iwDnp9q7", "0x123", false, "", 0);
addFile(1, "0x00", "cutepic", "QmTecWfmvvsPdZXuYrLgCTqRj9YgBiAUL4ZCr9iwDnp9q7", "0x123", false, "", 0);
addFile(1, "0x00", "awesome", "QmTecWfmvvsPdZXuYrLgCTqRj9YgBiAUL4ZCr9iwDnp9q7", "0x123", false, "", 0);
}
// Get Indexes with Names for EIN
// _for = 1 is Files, 2 is GroupFiles, 3 is Groups
function debugIndexesWithNames(uint _ein, uint _groupIndex, uint _seedPointer, uint16 _limit, bool _asc, uint8 _for)
external view
returns (uint[20] memory _indexes, string memory _names) {
if (_for == 1) {
_indexes = _getIndexes(fileOrder[_ein], _seedPointer, _limit, _asc);
}
else if (_for == 2) {
_indexes = _getIndexes(groups[_ein][_groupIndex].groupFilesOrder, _seedPointer, _limit, _asc);
}
else if (_for == 3) {
_indexes = _getIndexes(groupOrder[_ein], _seedPointer, _limit, _asc);
}
uint16 i = 0;
bool completed = false;
while (completed == false) {
string memory name;
// Get Name
if (_for == 1 || _for == 2) {
name = files[_ein][_indexes[i]].name;
}
else if (_for == 3) {
name = groups[_ein][_indexes[i]].name;
}
// Add To Return Vars
name = _append(name, "|");
_names = _append(_names, name);
i++;
// check status
if (i == _limit || (_indexes[i-1] == _indexes[i])) {
completed = true;
}
}
}
}
| Turn off the non-stich group | _orderMapping[_maxIndex].active = false;
| 2,542,364 | [
1,
15858,
3397,
326,
1661,
17,
334,
1354,
1041,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
389,
1019,
3233,
63,
67,
1896,
1016,
8009,
3535,
273,
629,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-08-12
*/
pragma solidity ^0.5.16;
// Modified from compound/ComptrollerInterface
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function checkMembership(address account, address cToken) external view returns (bool);
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function enterMarket(address cToken, address borrower) external returns (uint);
function exitMarket(address cToken) external returns (uint);
function getAccountAssets(address account) external view returns (address[] memory);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
// Copied from compound/InterestRateModel
/**
* @title DeFilend's InterestRateModel Interface
* @author DeFil
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
// Modified from compound/CTokenInterfaces
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
// uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice The keeper of the reserve
*/
address public reserveKeeper;
/**
* @notice The accrued reserves of each reserveKeeper in history
*/
mapping (address => uint) public historicalReserveKeeperAccrued;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserve keeper is changed
*/
event NewReserveKeeper(address oldReserveKeeper, address newReserveKeeper);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address keeper, address receiver, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _setReserveKeeper(address newReserveKeeper) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
}
contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
// Modified from Compound/ErrorReporter
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
INVALID_KEEPER_FACTOR,
INVALID_MARKET_PERCENTAGES,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK,
SET_DFL_KEEPER_OWNER_CHECK,
SET_DFL_KEEPER_FACTOR_OWNER_CHECK,
SET_DFL_KEEPER_FACTOR_VALIDATION,
SET_DFL_MARKET_PERCENTAGES_OWNER_CHECK,
SET_DFL_MARKET_PERCENTAGES_LENGTH_VALIDATION,
SET_DFL_MARKET_PERCENTAGES_SUM_VALIDATION
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
REJECTION,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
JUST_REJECTION,
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_ACCUMULATED_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
ACCRUE_INTEREST_RESERVE_KEEPER_ACCRUED_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
SET_RESERVE_KEEPER_ACCRUE_INTEREST_FAILED,
SET_RESERVE_KEEPER_ADMIN_CHECK,
SET_RESERVE_KEEPER_VALID_CHECK,
SET_RESERVE_KEEPER_FRESH_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
// Copied from compound/CarefulMath
/**
* @title Careful Math
* @author DeFil
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
// Copied from Compound/ExponentialNoError
/**
* @title Exponential module for storing fixed-precision decimals
* @author DeFil
* @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)});
}
}
// Copied from Compound/Exponential
/**
* @title Exponential module for storing fixed-precision decimals
* @author DeFil
* @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath, ExponentialNoError {
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
}
// Copied from compound/EIP20Interface
/**
* @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);
}
// Copied from compound/EIP20NonStandardInterface
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// Modified from compound/CToken
/**
* @title DeFilend's CToken Contract
* @notice Abstract base for CTokens
* @author DeFilend
*/
contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// set reserveKeeper
reserveKeeper = admin;
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) public view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
struct AccrueInterestLocalVars {
uint interestAccumulated;
uint reservesAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
uint currentReserveKeeperAccrued;
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
// require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
AccrueInterestLocalVars memory vars;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, vars.interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, vars.totalBorrowsNew) = addUInt(vars.interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, vars.reservesAccumulated) = mulScalarTruncate(Exp({mantissa: reserveFactorMantissa}), vars.interestAccumulated);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, vars.currentReserveKeeperAccrued) = addUInt(historicalReserveKeeperAccrued[reserveKeeper], vars.reservesAccumulated);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_RESERVE_KEEPER_ACCRUED_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, vars.totalReservesNew) = addUInt(vars.reservesAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, vars.borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = vars.borrowIndexNew;
totalBorrows = vars.totalBorrowsNew;
totalReserves = vars.totalReservesNew;
historicalReserveKeeperAccrued[reserveKeeper] = vars.currentReserveKeeperAccrued;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, vars.interestAccumulated, vars.borrowIndexNew, vars.totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and add reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
uint actualAddAmount = doTransferIn(msg.sender, addAmount);
// Store totalReserves
totalReserves = add_(totalReserves, actualAddAmount, "add reserves unexpected overflow");
// Added accrued reserves of admin
historicalReserveKeeperAccrued[admin] = add_(historicalReserveKeeperAccrued[admin], actualAddAmount, "add reserves of admin unexpected overflow");
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReserves);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to reserve keeper
* @param receiver Receiver of reduced reserves
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(address receiver, uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(receiver, reduceAmount);
}
/**
* @notice Reduces reserves by transferring to reserve keeper
* @dev Requires fresh interest accrual
* @param receiver Receiver of reduced reserves
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(address receiver, uint reduceAmount) internal returns (uint) {
address keeper = msg.sender;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves of reserveKeeper
if (reduceAmount > historicalReserveKeeperAccrued[keeper]) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Store totalReserves
totalReserves = sub_(totalReserves, reduceAmount, "sub reserves unexpected overflow");
// Sub accrued reserves of keeper
historicalReserveKeeperAccrued[keeper] = sub_(historicalReserveKeeperAccrued[keeper], reduceAmount, "sub reserves of keeper unexpected overflow");
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(receiver, reduceAmount);
emit ReservesReduced(keeper, receiver, reduceAmount, totalReserves);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the reserveKeeper
* @dev Admin function to accrue interest and update reserveKeeper
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveKeeper(address newReserveKeeper) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_RESERVE_KEEPER_ACCRUE_INTEREST_FAILED);
}
return _setReserveKeeperFresh(newReserveKeeper);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveKeeperFresh(address newReserveKeeper) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_KEEPER_ADMIN_CHECK);
}
// Check is valid address
if (newReserveKeeper == address(0)) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_KEEPER_VALID_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_KEEPER_FRESH_CHECK);
}
// old reserve keeper
address oldReserveKeeper = reserveKeeper;
// update reserveKeeper
reserveKeeper = newReserveKeeper;
emit NewReserveKeeper(oldReserveKeeper, newReserveKeeper);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
// Copied from compound/PriceOracle
contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a cToken asset
* @param cToken The cToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(CToken cToken) external view returns (uint);
}
// Modified from compound/ComptrollerStorage
contract UnitrollerAdminStorage {
// The address of DFL
address public dflAddress;
// The havle period in block number
uint public dflHalvePeriod;
// The speed (per block) when mining starts
uint public dflInitialSpeed;
// At when the dfl mining starts
uint public dflStartBlock;
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of Unitroller
*/
address public comptrollerImplementation;
/**
* @notice Pending brains of Unitroller
*/
address public pendingComptrollerImplementation;
}
contract ComptrollerStorage is UnitrollerAdminStorage {
/**
* @notice Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @notice Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @notice Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => CToken[]) public accountAssets;
struct Market {
/// @notice Whether or not this market is listed
bool isListed;
/**
* @notice Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be between 0 and 1, and stored as a mantissa.
*/
uint collateralFactorMantissa;
/// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
}
/**
* @notice Official mapping of cTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @notice The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
// -------- DFL correlations begin ---------
// Current speed (per block)
uint public dflCurrentSpeed;
// Block number that DFL was last accrued at
uint public dflAccrualBlock;
// The block number when next havle will happens
uint public dflNextHalveBlock;
// The address of keeper
address public dflKeeper;
// Percentage of DFLs that is set aside for keeper
uint public dflKeeperFactorMantissa;
/// @notice A list of all markets
CToken[] public allMarkets;
/// @notice Percentages of DFL allocated to each Market
uint[] public dflMarketPercentages;
/// @notice The DFL market supply index for each market
mapping(address => uint) public dflSupplyIndex;
/// @notice The DFL borrow index for each market for each supplier as of the last time they accrued DFL
mapping(address => mapping(address => uint)) public dflSupplierIndex;
/// @notice The DFL accrued but not yet transferred to each user
mapping(address => uint) public dflAccrued;
// -------- DFL correlations end ---------
// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.
address public borrowCapGuardian;
// @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint) public borrowCaps;
}
// Copied from compound/Unitroller
/**
* @title ComptrollerCore
* @dev storage for the comptroller will be at this address, and
* cTokens should reference this contract rather than a deployed implementation if
*
*/
contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter {
/**
* @notice Emitted when pendingComptrollerImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
constructor(address dflAddress_,
uint dflHalvePeriod_,
uint dflInitialSpeed_,
uint dflStartBlock_) public {
require(dflAddress_ != address(0), "dflAddress_");
require(dflHalvePeriod_ != 0, "dflHalvePeriod_");
require(dflInitialSpeed_ != 0, "dflInitialSpeed_");
require(dflStartBlock_ >= block.number, "dflStartBlock_");
// Set admin to caller
admin = msg.sender;
dflAddress = dflAddress_;
dflHalvePeriod = dflHalvePeriod_;
dflInitialSpeed = dflInitialSpeed_;
dflStartBlock = dflStartBlock_;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptImplementation() public returns (uint) {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
// Save current values for inclusion in log
address oldImplementation = comptrollerImplementation;
address oldPendingImplementation = pendingComptrollerImplementation;
comptrollerImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = address(0);
emit NewImplementation(oldImplementation, comptrollerImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*
* TODO: Should we add a second arg to verify, like a checksum of `newAdmin` address?
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
function () payable external {
// delegate all other functions to current implementation
(bool success, ) = comptrollerImplementation.delegatecall(msg.data);
// solium-disable-next-line security/no-inline-assembly
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
}
/**
* @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 {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == msg.sender, "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 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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// Modified from Compound/COMP
contract DFL is EIP20Interface, Ownable {
/// @notice EIP-20 token name for this token
string public constant name = "DeFIL-V2";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "DFL-V2";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint96 internal _totalSupply;
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 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 The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new DFL token
*/
constructor() public {
emit Transfer(address(0), address(this), 0);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
* Emits a {Transfer} event with `from` set to the zero address.
* @param account The address of the account holding the new funds
* @param rawAmount The number of tokens that are minted
*/
function mint(address account, uint rawAmount) public onlyOwner {
require(account != address(0), "DFL:: mint: cannot mint to the zero address");
uint96 amount = safe96(rawAmount, "DFL::mint: amount exceeds 96 bits");
_totalSupply = add96(_totalSupply, amount, "DFL::mint: total supply exceeds");
balances[account] = add96(balances[account], amount, "DFL::mint: mint amount exceeds balance");
_moveDelegates(address(0), delegates[account], amount);
emit Transfer(address(0), account, amount);
}
/** @dev Burns `amount` tokens, decreasing the total supply.
* @param rawAmount The number of tokens that are bruned
*/
function burn(uint rawAmount) external {
uint96 amount = safe96(rawAmount, "DFL::burn: amount exceeds 96 bits");
_totalSupply = sub96(_totalSupply, amount, "DFL::burn: total supply exceeds");
balances[msg.sender] = sub96(balances[msg.sender], amount, "DFL::burn: burn amount exceeds balance");
_moveDelegates(delegates[msg.sender], address(0), amount);
emit Transfer(msg.sender, address(0), amount);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "DFL::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the total supply of tokens
* @return The total supply of tokens
*/
function totalSupply() external view returns (uint) {
return _totalSupply;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "DFL::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "DFL::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "DFL::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "DFL::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "DFL::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "DFL::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 (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "DFL::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];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "DFL::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "DFL::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "DFL::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "DFL::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "DFL::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "DFL::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "DFL::_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 safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
interface Distributor {
// The asset to be distributed
function asset() external view returns (address);
// Return the accrued amount of account based on stored data
function accruedStored(address account) external view returns (uint);
// Accrue and distribute for caller, but not actually transfer assets to the caller
// returns the new accrued amount
function accrue() external returns (uint);
// Claim asset, transfer the given amount assets to receiver
function claim(address receiver, uint amount) external returns (uint);
}
// Modified from compound/Comptroller.sol
/**
* @title Defilend's Comptroller Contract
* @author Defilend
*/
contract Comptroller is ComptrollerStorage, ComptrollerInterface, ComptrollerErrorReporter, ExponentialNoError, Distributor {
/// @notice Emitted when an admin supports a market
event MarketListed(CToken cToken);
/// @notice Emitted when an account enters a market
event MarketEntered(CToken cToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(CToken cToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(CToken cToken, string action, bool pauseState);
/// @notice Emitted when dflKeeper is changed
event NewDflKeeper(address oldDflKeeper, address newDflKeeper);
/// @notice Emitted when dflKeeperFactorMantissa is changed
event NewDflKeeperFactor(uint oldDflKeeperFactorMantissa, uint newDflKeeperFactorMantissa);
/// @notice Emitted when market percentages is changed
event NewDflMarketPercentage(CToken cToken, uint oldPercentage, uint newPercentage);
// Event emitted when DFL is accrued
event AccrueDFL(uint keeperPart, uint marketsPart);
/// @notice Emitted when DFL is distributed to a supplier
event DistributedSupplierDFL(CToken cToken, address supplier, uint dflDelta, uint dflSupplyIndex);
/// @notice Emitted when DFL is claimed by account
event ClaimedDFL(address account, address receiver, uint amount);
/// @notice Emitted when borrow cap for a cToken is changed
event NewBorrowCap(CToken cToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice The initial DFL index for a market
uint224 public constant dflInitialIndex = 1e36;
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// dflKeeperFactorMantissa must be little equal this value
uint internal constant dflKeeperFactorMaxMantissa = 0.9e18; // 0.9
constructor() public {
admin = msg.sender;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (CToken[] memory) {
CToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param cToken The cToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, address cToken) external view returns (bool) {
return markets[cToken].accountMembership[account];
}
/**
* @notice Add asset to be included in account liquidity calculation
* @param cToken The address of the cToken market to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarket(address cToken, address borrower) external returns (uint) {
require(msg.sender == cToken, "sender must be cToken");
return uint(addToMarketInternal(CToken(cToken), borrower));
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param cTokens The list of addresses of the cToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory) {
uint len = cTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
CToken cToken = CToken(cTokens[i]);
results[i] = uint(addToMarketInternal(cToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param cToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(cToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(cToken);
emit MarketEntered(cToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param cTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address cTokenAddress) external returns (uint) {
CToken cToken = CToken(cTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the cToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(cToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set cToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete cToken from the account’s list of assets */
// load into memory for faster iteration
CToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == cToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
CToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.length--;
emit MarketExited(cToken, msg.sender);
return uint(Error.NO_ERROR);
}
function getAccountAssets(address account) external view returns (address[] memory) {
CToken[] memory assets = accountAssets[account];
address[] memory addresses = new address[](assets.length);
for (uint i = 0; i < assets.length; i++) {
addresses[i] = address(assets[i]);
}
return addresses;
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param cToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[cToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
accrueDFL();
distributeSupplierDFL(cToken, minter);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param cToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
cToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param cToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of cTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) {
uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
accrueDFL();
distributeSupplierDFL(cToken, redeemer);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[cToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param cToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external {
// Shh - currently unused
cToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param cToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[cToken], "borrow is paused");
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[cToken].accountMembership[borrower]) {
// only cTokens may call borrowAllowed if borrower not in market
require(msg.sender == cToken, "sender must be cToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(CToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[cToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[cToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = CToken(cToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param cToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address cToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
cToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param cToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param cToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
// Shh - currently unused
cToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower);
uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
cTokenBorrowed;
cTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
// Keep the flywheel moving
accrueDFL();
distributeSupplierDFL(cTokenCollateral, borrower);
distributeSupplierDFL(cTokenCollateral, liquidator);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
cTokenCollateral;
cTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param cToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(cToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
accrueDFL();
distributeSupplierDFL(cToken, src);
distributeSupplierDFL(cToken, dst);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param cToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
*/
function transferVerify(address cToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
cToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `cTokenBalance` is the number of cTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint cTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address cTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
CToken cTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
// For each asset the account is in
CToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
CToken asset = assets[i];
// Read the balances and exchange rate from the cToken
(oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * cTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with cTokenModify
if (asset == cTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in cToken.liquidateBorrowFresh)
* @param cTokenBorrowed The address of the borrowed cToken
* @param cTokenCollateral The address of the collateral cToken
* @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens
* @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}));
denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));
ratio = div_(numerator, denominator);
seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param cToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(cToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param cToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(CToken cToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(cToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
cToken.isCToken(); // Sanity check to make sure its really a CToken
markets[address(cToken)] = Market({isListed: true, collateralFactorMantissa: 0});
_addMarketInternal(address(cToken));
emit MarketListed(cToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address cToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != CToken(cToken), "market already added");
}
allMarkets.push(CToken(cToken));
dflMarketPercentages.push(0);
dflSupplyIndex[cToken] = dflInitialIndex;
}
/**
* @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param cTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(CToken[] calldata cTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps");
uint numMarkets = cTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(cTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(cTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
require(msg.sender == admin, "only admin can set borrow cap guardian");
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Mint", state);
return state;
}
function _setBorrowPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
/**
* @notice Admin function to change dflKeeper address
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setDflKeeper(address newDflKeeper) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_DFL_KEEPER_OWNER_CHECK);
}
// accrue
accrueDFL();
// Save current value for inclusion in log
address oldDflKeeper = dflKeeper;
// Store new DFL keeper
dflKeeper = newDflKeeper;
// Emit event
emit NewDflKeeper(oldDflKeeper, newDflKeeper);
return uint(Error.NO_ERROR);
}
/**
* @notice Admin function to change dflKeeperFactorMantissa
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setDflKeeperFactor(uint newDflKeeperFactorMantissa) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_DFL_KEEPER_FACTOR_OWNER_CHECK);
}
// Check newDflKeeperFactorMantissa
if (newDflKeeperFactorMantissa > dflKeeperFactorMaxMantissa) {
return fail(Error.INVALID_KEEPER_FACTOR, FailureInfo.SET_DFL_KEEPER_FACTOR_VALIDATION);
}
// accrue
accrueDFL();
// Save current value for inclusion in log
uint oldDflKeeperFactorMantissa = dflKeeperFactorMantissa;
// Store new values
dflKeeperFactorMantissa = newDflKeeperFactorMantissa;
// Emit event
emit NewDflKeeperFactor(oldDflKeeperFactorMantissa, newDflKeeperFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Admin function to change percentages of markets
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setDflMarketPercentages(uint[] calldata newDflMarketPercentages) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_DFL_MARKET_PERCENTAGES_OWNER_CHECK);
}
// reference storage
uint[] storage storedPercentages = dflMarketPercentages;
if (newDflMarketPercentages.length != storedPercentages.length) {
return fail(Error.INVALID_MARKET_PERCENTAGES, FailureInfo.SET_DFL_MARKET_PERCENTAGES_LENGTH_VALIDATION);
}
uint sumNewMarketPercentageMantissa;
for (uint i = 0; i < newDflMarketPercentages.length; i++) {
sumNewMarketPercentageMantissa = add_(sumNewMarketPercentageMantissa, newDflMarketPercentages[i]);
}
// Check sumNewMarketPercentageMantissa == mantissaOne
if (sumNewMarketPercentageMantissa != mantissaOne) {
return fail(Error.INVALID_MARKET_PERCENTAGES, FailureInfo.SET_DFL_MARKET_PERCENTAGES_SUM_VALIDATION);
}
// accrue
accrueDFL();
for (uint i = 0; i < newDflMarketPercentages.length; i++) {
CToken cToken = allMarkets[i];
uint oldPercentage = storedPercentages[i];
storedPercentages[i] = newDflMarketPercentages[i];
emit NewDflMarketPercentage(cToken, oldPercentage, newDflMarketPercentages[i]);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == comptrollerImplementation;
}
/*** DFL Distribution ***/
// accrue DFL
function accrueDFL() internal {
uint currentBlock = getBlockNumber();
// Check if it's time to start mining
if (currentBlock < dflStartBlock) {
return;
}
if (dflAccrualBlock == 0) {
dflCurrentSpeed = dflInitialSpeed; // initial speed
dflAccrualBlock = dflStartBlock;
dflNextHalveBlock = dflStartBlock + dflHalvePeriod;
}
uint startBlock;
uint endBlock = dflAccrualBlock;
while (endBlock < currentBlock) {
startBlock = endBlock;
if (currentBlock < dflNextHalveBlock) {
endBlock = currentBlock;
} else {
endBlock = dflNextHalveBlock;
}
accrueDflFresh(startBlock, endBlock);
if (endBlock == dflNextHalveBlock) {
dflCurrentSpeed = dflCurrentSpeed / 2;
dflNextHalveBlock = dflNextHalveBlock + dflHalvePeriod;
}
}
dflAccrualBlock = currentBlock;
}
function accrueDflFresh(uint startBlock, uint endBlock) internal {
uint deltaBlocks = sub_(endBlock, startBlock);
if (deltaBlocks > 0) {
uint deltaDFLs = mul_(deltaBlocks, dflCurrentSpeed);
DFL(dflAddress).mint(address(this), deltaDFLs);
uint keeperPart = div_(mul_(dflKeeperFactorMantissa, deltaDFLs), mantissaOne);
uint suppliersPart = sub_(deltaDFLs, keeperPart);
// update dflKeeper accrued
dflAccrued[dflKeeper] = add_(dflAccrued[dflKeeper], keeperPart);
CToken[] memory markets = allMarkets;
uint[] memory percentages = dflMarketPercentages;
for (uint i = 0; i < markets.length; i ++) {
address theMarket = address(markets[i]);
uint thePercentage = percentages[i];
if (thePercentage > 0) {
uint thisPart = div_(mul_(thePercentage, suppliersPart), mantissaOne);
uint supplyTokens = CToken(theMarket).totalSupply();
Double memory ratio = supplyTokens > 0 ? fraction(thisPart, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: dflSupplyIndex[theMarket]}), ratio);
dflSupplyIndex[theMarket] = index.mantissa;
}
}
emit AccrueDFL(keeperPart, suppliersPart);
}
}
/**
* @notice Calculate DFL accrued by a supplier
* @param cToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute DFL to
*/
function distributeSupplierDFL(address cToken, address supplier) internal {
(uint supplierDelta, uint supplyIndex) = supplierDeltaDflStored(cToken, supplier);
uint supplierAccrued = add_(dflAccrued[supplier], supplierDelta);
// update index and accrued
dflSupplierIndex[cToken][supplier] = supplyIndex;
dflAccrued[supplier] = supplierAccrued;
emit DistributedSupplierDFL(CToken(cToken), supplier, supplierDelta, supplyIndex);
}
/// @notice Calculate delta DFL accrued by a supplier
function supplierDeltaDflStored(address cToken, address supplier) internal view returns(uint, uint) {
Double memory supplyIndex = Double({mantissa: dflSupplyIndex[cToken]});
Double memory supplierIndex = Double({mantissa: dflSupplierIndex[cToken][supplier]});
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = dflInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = CToken(cToken).balanceOf(supplier);
return (mul_(supplierTokens, deltaIndex), supplyIndex.mantissa);
}
/*** Distributor implementation begin ***/
function asset() external view returns (address) {
return dflAddress;
}
function accruedStored(address account) public view returns (uint) {
uint accrued = dflAccrued[account];
CToken[] memory markets = allMarkets;
for (uint i = 0; i < markets.length; i++) {
(uint supplierDelta, ) = supplierDeltaDflStored(address(markets[i]), account);
accrued = add_(accrued, supplierDelta);
}
return accrued;
}
function accrue() external returns (uint) {
accrueDFL();
return accruedStored(msg.sender);
}
function claim(address receiver, uint amount) external returns (uint) {
address account = msg.sender;
// accrue first
accrueDFL();
CToken[] memory markets = allMarkets;
for (uint i = 0; i < markets.length; i++) {
CToken cToken = markets[i];
distributeSupplierDFL(address(cToken), account);
}
require(amount <= dflAccrued[account], "insufficent value");
// check cash
DFL dfl = DFL(dflAddress);
require(amount <= dfl.balanceOf(address(this)), "insufficent cash");
// do transfer
dfl.transfer(receiver, amount);
// update storage
dflAccrued[account] = sub_(dflAccrued[account], amount);
emit ClaimedDFL(account, receiver, amount);
return amount;
}
/*** Distributor implementation end ***/
function claimDFL() external {
address account = msg.sender;
// accrue first
accrueDFL();
CToken[] memory markets = allMarkets;
for (uint i = 0; i < markets.length; i++) {
CToken cToken = markets[i];
distributeSupplierDFL(address(cToken), account);
}
// claim amount
uint amount = dflAccrued[account];
// check cash
DFL dfl = DFL(dflAddress);
require(amount <= dfl.balanceOf(address(this)), "insufficent cash");
// do transfer
dfl.transfer(account, amount);
// update storage
dflAccrued[account] = 0;
emit ClaimedDFL(account, account, amount);
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (CToken[] memory) {
return allMarkets;
}
/**
* @notice Return dfl percentage of all markets
* @return The list of dfl percentages
*/
function getDflMarketPercentages() public view returns (uint[] memory) {
return dflMarketPercentages;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
} | ** Distributor implementation begin ***/ | function asset() external view returns (address) {
return dflAddress;
}
| 6,703,814 | [
1,
1669,
19293,
4471,
2376,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3310,
1435,
3903,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
302,
2242,
1887,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.24;
import "../interfaces/ComponentContainerInterface.sol";
import "../interfaces/FutureInterfaceV1.sol";
import "../interfaces/LockerInterface.sol";
import "../libs/ERC20NoReturn.sol";
import "../interfaces/ComponentListInterface.sol";
import "../interfaces/ReimbursableInterface.sol";
import "../interfaces/StepInterface.sol";
import "../interfaces/MarketplaceInterface.sol";
import "../BaseDerivative.sol";
import "zeppelin-solidity/contracts/ownership/Ownable.sol";
import "./tokens/FutureERC721Token.sol";
contract FutureContract is BaseDerivative, FutureInterfaceV1 {
using SafeMath for uint256;
uint public constant DENOMINATOR = 10000;
uint public constant TOKEN_DENOMINATOR = 10**18;
uint public constant INITIAL_FEE = 10**17;
// Enum and constants
int public constant LONG = -1;
int public constant SHORT = 1;
enum CheckPositionPhases { Initial, LongTokens, ShortTokens }
enum ClearPositionPhases { Initial, CalculateLoses, CalculateBenefits }
// Action of the Future
bytes32 public constant CLEAR = "Clear";
bytes32 public constant CHECK_POSITION = "CheckPosition";
// Basic information that is override on creation
string public name = "Olympus Future";
string public description = "Olympus Future";
string public version = "v0.1";
string public symbol;
// Config on Creation
uint public target;
address public targetAddress;
uint public targetPrice;
uint public deliveryDate;
uint public depositPercentage;
uint public forceClosePositionDelta;
uint public amountOfTargetPerShare;
// Information of the tokens and balance
FutureERC721Token public longToken;
FutureERC721Token public shortToken;
uint public winnersBalance;
// Manager balance for reiumursable
uint public accumulatedFee;
// Check position frozen data
uint[] public frozenLongTokens;
uint[] public frozenShortTokens;
// TODO: Maybe struct will compact for optimizing (but will need getters)
uint public frozenPrice; // Keep same price on clear and check position.
uint public frozenTotalWinnersSupply; // To check the percentage of each winner
uint public winnersBalanceRedeemed; // To check at the end decimals or not winers
// TODO: Change this event for real transfer to user holder OL-1369
event DepositReturned(int _direction, uint _tokenId, uint amount);
event Benefits(int _direction, address _holder, uint amount);
constructor(
string _name,
string _description,
string _symbol,
bytes32 _category,
uint _target,
address _targetAddress,
uint _amountOfTargetPerShare,
uint _depositPercentage,
uint _forceClosePositionDelta
) public {
name = _name;
description = _description;
symbol = _symbol;
category = _category;
target = _target;
targetAddress = _targetAddress;
amountOfTargetPerShare = _amountOfTargetPerShare;
depositPercentage = _depositPercentage;
forceClosePositionDelta = _forceClosePositionDelta;
//
status = DerivativeStatus.New;
fundType = DerivativeType.Future;
}
/// --------------------------------- INITIALIZE ---------------------------------
function initialize(address _componentList, uint _deliveryDate) public payable {
require(status == DerivativeStatus.New, "1");
// Require some balance for internal operations such as reimbursable
require(msg.value >= INITIAL_FEE, "2");
_initialize(_componentList);
bytes32[4] memory _names = [MARKET, LOCKER, REIMBURSABLE, STEP];
for (uint i = 0; i < _names.length; i++) {
updateComponent(_names[i]);
}
deliveryDate = _deliveryDate; // Not sure we need, is hold also in the interval
uint[] memory _intervals = new uint[](2);
bytes32[] memory _intervalCategories = new bytes32[](2);
_intervals[0] = _deliveryDate;
_intervals[1] = 20 minutes;
_intervalCategories[0] = CLEAR;
_intervalCategories[1] = CHECK_POSITION;
LockerInterface(getComponentByName(LOCKER)).setMultipleTimeIntervals(_intervalCategories, _intervals);
checkLocker(CLEAR); // Execute the timer so gets intialized
MarketplaceInterface(getComponentByName(MARKET)).registerProduct();
setMaxSteps(CHECK_POSITION, 10);
// Create here ERC721
initializeTokens();
status = DerivativeStatus.Active;
accumulatedFee = accumulatedFee.add(msg.value);
}
function initializeTokens() internal {
longToken = new FutureERC721Token(name, symbol, LONG);
shortToken = new FutureERC721Token(name, symbol, SHORT);
}
/// --------------------------------- END INITIALIZE ---------------------------------
/// --------------------------------- ORACLES ---------------------------------
function getTargetPrice() public view returns(uint) {
return targetPrice;
}
/// --------------------------------- END ORACLES ---------------------------------
/// --------------------------------- TOKENS ---------------------------------
function getToken(int _direction) public view returns(FutureERC721Token) {
if(_direction == LONG) {return longToken; }
if(_direction == SHORT) {return shortToken; }
revert();
}
function isTokenValid(int _direction, uint _id) public view returns(bool) {
return getToken(_direction).isTokenValid(_id);
}
function ownerOf(int _direction, uint _id) public view returns(address) {
return getToken(_direction).ownerOf(_id);
}
function getTokenDeposit(int _direction, uint _id) public view returns(uint) {
return getToken(_direction).getDeposit(_id);
}
function getValidTokens(int _direction) public view returns(uint[] memory) {
return getToken(_direction).getValidTokens();
}
function getTokenIdsByOwner(int _direction, address _owner) internal view returns (uint[] memory) {
return getToken(_direction).getTokenIdsByOwner(_owner);
}
function invalidateTokens(int _direction, uint[] memory _tokens) internal {
return getToken(_direction).invalidateTokens(_tokens);
}
function getValidTokenIdsByOwner(int _direction, address _owner) internal view returns (uint[] memory) {
return getToken(_direction).getValidTokenIdsByOwner(_owner);
}
function getTokenActualValue(int _direction, uint _id, uint _price) public view returns(uint) {
if(!isTokenValid(_direction, _id)) {return 0;}
uint _startPrice = getToken(_direction).getBuyingPrice(_id);
uint _tokenDeposit = getTokenDeposit(_direction, _id);
// We avoid the negative numbers
uint _priceDifference;
if(_startPrice > _price) {_priceDifference = _startPrice.sub(_price);}
else {_priceDifference = _price.sub(_startPrice);}
/**
* TOKEN_DENOMINATOR. (We start multiplying for the precision, as we will finis dividing)
* .mul(_priceDifference.div(_startPrice)) We multiply per the percentage of price changed
(price changed 2% since we buy for example)
* .mul (DENOMINATOR.div(tokenDeposit)) We multuply per the % of the deposit.
So if the deposit represents 5%, reduce price of 2% means a 10% of deposit reduction.
* .mul(tokenDeposit) OurToken depoist multiplied 10% reduction, gets his real value (90% of the starting deposit)
* .div(TOKEN_DENOMINATOR) Eliminate the precision.
* All this simplify is the next formula
*/
uint _depositUpdate = TOKEN_DENOMINATOR
.mul(_priceDifference)
.mul(DENOMINATOR)
.mul(_tokenDeposit)
.div(_startPrice.mul(depositPercentage).mul(TOKEN_DENOMINATOR))
;
// LONG and Positive OR short and Negative
if((_direction == LONG && _startPrice > _price) || (_direction == SHORT && _startPrice < _price)) {
if(_tokenDeposit <= _depositUpdate) {return 0;}
return _tokenDeposit.sub(_depositUpdate);
}
// Else
return _tokenDeposit.add(_depositUpdate);
}
function getTokenBottomPosition(int _direction, uint _id) public view returns(uint) {
uint deposit = getTokenDeposit(_direction, _id);
return deposit.sub(deposit.mul(forceClosePositionDelta).div(DENOMINATOR)); // This DENOMINATOR is based on the deposit
}
// This will check all the tokens and execute the function passed as parametter
// Require to freezeLong and freezeShort tokens before and will delete them on finish
function checkTokens(
function (int, uint) internal returns(bool) checkFunction
) internal returns (bool) {
uint i;
uint _transfers = initializeOrContinueStep(CHECK_POSITION);
CheckPositionPhases _stepStatus = CheckPositionPhases(getStatusStep(CHECK_POSITION));
// CHECK VALID LONG TOKENS
if(_stepStatus == CheckPositionPhases.LongTokens) {
for (i = _transfers; i < frozenLongTokens.length && goNextStep(CHECK_POSITION); i++) {
checkFunction(LONG, frozenLongTokens[i]);
}
if(i == frozenLongTokens.length) {
_stepStatus = CheckPositionPhases(updateStatusStep(CHECK_POSITION));
_transfers = 0;
}
}
// CHECK VALID SHORT TOKENS
if(_stepStatus == CheckPositionPhases.ShortTokens) {
for (i = _transfers; i < frozenShortTokens.length && goNextStep(CHECK_POSITION); i++) {
checkFunction(SHORT, frozenShortTokens[i]);
}
// FINISH
if(i == frozenShortTokens.length) {
finalizeStep(CHECK_POSITION);
delete frozenShortTokens;
delete frozenLongTokens;
return true;
}
}
// NOT FINISH
return false;
}
/// --------------------------------- END TOKENS ---------------------------------
/// --------------------------------- INVEST ---------------------------------
function invest(
int _direction, // long or short
uint _shares // shares of the target.
) external payable returns (bool) {
uint _targetPrice = getTargetPrice();
require( status == DerivativeStatus.Active,"3");
require(_targetPrice > 0, "4");
uint _totalEthDeposit = calculateShareDeposit(_shares, _targetPrice);
require(msg.value >= _totalEthDeposit ,"5"); // Enough ETH to buy the share
require(
getToken(_direction).mintMultiple(
msg.sender,
_totalEthDeposit.div(_shares),
_targetPrice,
_shares
) == true, "6");
// Return maining ETH to the token
msg.sender.transfer(msg.value.sub(_totalEthDeposit));
return true;
}
// Return the value required to buy a share to a current price
function calculateShareDeposit(uint _amountOfShares, uint _targetPrice) public view returns(uint) {
return _amountOfShares
.mul(amountOfTargetPerShare)
.mul(_targetPrice)
.mul(depositPercentage)
.div(DENOMINATOR); // Based on the deposit
}
/// --------------------------------- END INVEST ---------------------------------
/// --------------------------------- CHECK POSITION ---------------------------------
function checkPosition() external returns (bool) {
startGasCalculation();
require(status != DerivativeStatus.Closed, "7");
// INITIALIZE
CheckPositionPhases _stepStatus = CheckPositionPhases(getStatusStep(CHECK_POSITION));
if (_stepStatus == CheckPositionPhases.Initial) {
checkLocker(CHECK_POSITION);
frozenLongTokens = getValidTokens(LONG);
frozenShortTokens = getValidTokens(SHORT);
if (frozenLongTokens.length.add(frozenShortTokens.length) == 0) {
reimburse();
return true;
}
frozenPrice = getTargetPrice();
}
bool completed = checkTokens(checkTokenValidity);
if(completed) {
frozenPrice = 0;
}
reimburse();
return completed;
}
function checkTokenValidity(int _direction, uint _id) internal returns(bool){
if(!isTokenValid(_direction, _id)) {return false;} // Check if was already invalid
uint _tokenValue = getTokenActualValue(_direction, _id, frozenPrice);
uint _redLine = getTokenBottomPosition(_direction, _id);
// Is valid
if(_tokenValue > _redLine) { return true;}
// is Invalid
// Deliver the lasting value to the user
if(_tokenValue > 0){
ownerOf(_direction, _id).transfer(_tokenValue); // TODO when token get holder OL-1369
emit DepositReturned(_direction, _id, _tokenValue);
}
getToken(_direction).invalidateToken(_id);
// Keep the lost investment into the winner balance
winnersBalance = winnersBalance.add(getTokenDeposit(_direction, _id).sub(_tokenValue));
return false;
}
/// --------------------------------- END CHECK POSITION ---------------------------------
/// --------------------------------- CLEAR ---------------------------------
// for bot.
function clear() external returns (bool) {
startGasCalculation();
ClearPositionPhases _stepStatus = ClearPositionPhases(getStatusStep(CLEAR));
// INITIALIZE
if (_stepStatus == ClearPositionPhases.Initial) {
require(status != DerivativeStatus.Closed);
checkLocker(CLEAR);
status = DerivativeStatus.Closed;
frozenLongTokens = getValidTokens(LONG);
frozenShortTokens = getValidTokens(SHORT);
if (frozenLongTokens.length.add(frozenShortTokens.length) == 0) {
// TODO: Special case, no winners, what to do with winnerBalance?
accumulatedFee = accumulatedFee.add(winnersBalance);
unfreezeClear();
reimburse();
return true;
}
frozenPrice = getTargetPrice();
require(frozenPrice > 0);
_stepStatus = ClearPositionPhases(updateStatusStep(CLEAR));
}
// CHECK LOSERS
if(_stepStatus == ClearPositionPhases.CalculateLoses) {
if(checkTokens(checkLosersOnClear)) {
_stepStatus = ClearPositionPhases(updateStatusStep(CLEAR));
// Get the valid tokens, withouth the losers
frozenLongTokens = getValidTokens(LONG);
frozenShortTokens = getValidTokens(SHORT);
frozenTotalWinnersSupply = frozenLongTokens.length.add(frozenShortTokens.length);
winnersBalanceRedeemed = 0; // We start to redeem now
reimburse();
return false;
}
}
// CHECK WINNERS
if(_stepStatus == ClearPositionPhases.CalculateBenefits) {
if(checkTokens(checkWinnersOnClear)) {
finalizeStep(CLEAR);
if(winnersBalanceRedeemed == 0) {
// TODO: no winners (give to the manager?)
accumulatedFee = accumulatedFee.add(winnersBalance);
}
unfreezeClear();
reimburse();
return true;
}
}
// NOT FINISHED
reimburse();
return false;
}
function unfreezeClear() internal {
frozenTotalWinnersSupply = 0;
winnersBalance = 0;
frozenPrice = 0;
winnersBalanceRedeemed = 0;
}
function checkLosersOnClear(int _direction, uint _id) internal returns(bool) {
if(!isTokenValid(_direction, _id)) {return false;} // Check if was already invalid
uint _tokenValue = getTokenActualValue(_direction, _id, frozenPrice);
uint _tokenDeposit = getTokenDeposit(_direction, _id);
// Is winner
if(_tokenValue > _tokenDeposit) { return false;}
// Is loser
// Deliver the lasting value to the user
if(_tokenValue > 0){
ownerOf(_direction, _id).transfer(_tokenValue); // TODO when token get holder OL-1369
emit DepositReturned(_direction, _id, _tokenValue);
}
getToken(_direction).invalidateToken(_id);
// Keep the lost investment into the winner balance
winnersBalance = winnersBalance.add(_tokenDeposit.sub(_tokenValue));
return true;
}
// We check token by token, but in one go with process all tokens of the same holder
function checkWinnersOnClear(int _direction, uint _id) internal returns(bool) {
if(!isTokenValid(_direction, _id)) {return false;} // Check if was already invalid
uint _tokenValue = getTokenActualValue(_direction, _id, frozenPrice);
uint _tokenDeposit = getTokenDeposit(_direction, _id);
// Is loser (in theory shall be already out)
if(_tokenValue <= _tokenDeposit) { return false;}
address _holder = ownerOf(_direction, _id);
// TODO: maybe is good idea to reafctor invalidateTokensByOwner and get the valid num
uint[] memory _validTokens = getValidTokenIdsByOwner(_direction, _holder);
uint _ethToReturn = calculateBenefits(_direction, _validTokens);
invalidateTokens(_direction, _validTokens);
_holder.transfer(_ethToReturn);
emit Benefits(_direction, _holder, _ethToReturn);
return false;
}
function calculateBenefits(int _direction, uint[] _winnerTokens) internal returns(uint) {
uint _total;
uint _deposit;
uint _pendingBalance;
// We return all the deposit of the token winners + the benefits
for(uint i = 0; i < _winnerTokens.length; i++) {
_deposit = getTokenDeposit(_direction,_winnerTokens[i]);
_total = _total.add(_deposit);
}
// Benefits in function of his total supply
// Is important winners balance doesnt reduce, as is frozen during clear.
uint _benefits = winnersBalance.mul(_winnerTokens.length).div(frozenTotalWinnersSupply);
winnersBalanceRedeemed = winnersBalanceRedeemed.add(_benefits); // Keep track
// Special cases decimals
_pendingBalance = winnersBalance.sub(winnersBalanceRedeemed);
if(_pendingBalance > 0 && _pendingBalance < frozenTotalWinnersSupply) {
_benefits = _benefits.add(_pendingBalance);
}
return _total.add(_benefits);
}
/// --------------------------------- END CLEAR ---------------------------------
/// --------------------------------- ASSETS VALUE ---------------------------------
function getTotalAssetValue(int /*_direction*/) external view returns (uint) {
return 0;
}
// in ETH
function getMyAssetValue(int _direction) external view returns (uint){
uint[] memory tokens = getTokenIdsByOwner(_direction, msg.sender);
uint price = getTargetPrice();
uint balance;
for(uint i = 0; i < tokens.length; i++) {
balance = balance.add(getTokenActualValue(_direction, tokens[i], price));
}
return balance;
}
/// --------------------------------- END ASSETS VALUE ---------------------------------
/// --------------------------------- GETTERS ---------------------------------
// This is fullfulling the interface
function getName() external view returns (string) { return name; }
function getDescription() external view returns (string) { return description; }
function getTarget() external view returns (uint) {return target; }// an internal Id
function getTargetAddress() external view returns (address) { return targetAddress; } // if it’s ERC20, give it an address, otherwise 0x0
function getDeliveryDate() external view returns (uint) { return deliveryDate; } // timestamp
function getDepositPercentage() external view returns (uint) {return depositPercentage; }// 100 of 10000
function getAmountOfTargetPerShare() external view returns (uint) { return amountOfTargetPerShare;}
function getLongToken() external view returns (ERC721) {return longToken; }
function getShortToken() external view returns (ERC721) {return shortToken; }
// This can be removed for optimization if required
// Only help to check interal algorithm value, but is not for use of the final user.
// Client side could just fech them one buy one in a loop.
function getFrozenTokens(int _direction) external view returns(uint[]) {
if(_direction == LONG) { return frozenLongTokens;}
if(_direction == SHORT) { return frozenShortTokens;}
revert("8");
}
/// --------------------------------- END GETTERS ---------------------------------
/// --------------------------------- CONTRACTS CALLS ---------------------------------
// Rebalance
function startGasCalculation() internal {
ReimbursableInterface(getComponentByName(REIMBURSABLE)).startGasCalculation();
}
function reimburse() private {
uint reimbursedAmount = ReimbursableInterface(getComponentByName(REIMBURSABLE)).reimburse();
accumulatedFee = accumulatedFee.sub(reimbursedAmount);
msg.sender.transfer(reimbursedAmount);
}
// Locker and Step
function checkLocker(bytes32 category) internal {
LockerInterface(getComponentByName(LOCKER)).checkLockerByTime(category);
}
function initializeOrContinueStep(bytes32 category) internal returns(uint) {
return StepInterface(ReimbursableInterface(getComponentByName(STEP))).initializeOrContinue(category);
}
function getStatusStep(bytes32 category) internal view returns(uint) {
return StepInterface(ReimbursableInterface(getComponentByName(STEP))).getStatus(category);
}
function finalizeStep(bytes32 category) internal returns(bool) {
return StepInterface(ReimbursableInterface(getComponentByName(STEP))).finalize(category);
}
function goNextStep(bytes32 category) internal returns(bool) {
return StepInterface(ReimbursableInterface(getComponentByName(STEP))).goNextStep(category);
}
function updateStatusStep(bytes32 category) internal returns(uint) {
return StepInterface(ReimbursableInterface(getComponentByName(STEP))).updateStatus(category);
}
function setMaxSteps( bytes32 _category,uint _maxSteps) public onlyOwner {
StepInterface(getComponentByName(STEP)).setMaxCalls(_category, _maxSteps);
}
/// --------------------------------- END CONTRACTS CALLS ---------------------------------
/// --------------------------------- MANAGER ---------------------------------
// Payable
function() public payable {
revert();
}
function getManagerFee(uint _amount) external returns(bool) {
require(_amount > 0, "9" );
require(
status == DerivativeStatus.Closed ? // everything is done, take all.
(_amount <= accumulatedFee)
:
(_amount.add(INITIAL_FEE) <= accumulatedFee) // else, the initial fee stays.
, "10");
accumulatedFee = accumulatedFee.sub(_amount);
owner.transfer(_amount);
return true;
}
// For reiumbursable
function addOwnerBalance() external payable {
accumulatedFee = accumulatedFee.add(msg.value);
}
/// --------------------------------- END MANAGER ---------------------------------
}
| We return all the deposit of the token winners + the benefits | function calculateBenefits(int _direction, uint[] _winnerTokens) internal returns(uint) {
uint _total;
uint _deposit;
uint _pendingBalance;
for(uint i = 0; i < _winnerTokens.length; i++) {
_deposit = getTokenDeposit(_direction,_winnerTokens[i]);
_total = _total.add(_deposit);
}
if(_pendingBalance > 0 && _pendingBalance < frozenTotalWinnersSupply) {
_benefits = _benefits.add(_pendingBalance);
}
return _total.add(_benefits);
}
| 6,383,840 | [
1,
3218,
327,
777,
326,
443,
1724,
434,
326,
1147,
5657,
9646,
397,
326,
27641,
18352,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4604,
38,
4009,
18352,
12,
474,
389,
9855,
16,
2254,
8526,
389,
91,
7872,
5157,
13,
2713,
225,
1135,
12,
11890,
13,
288,
203,
203,
3639,
2254,
389,
4963,
31,
203,
3639,
2254,
389,
323,
1724,
31,
203,
3639,
2254,
389,
9561,
13937,
31,
203,
3639,
364,
12,
11890,
277,
273,
374,
31,
277,
411,
389,
91,
7872,
5157,
18,
2469,
31,
277,
27245,
288,
203,
5411,
389,
323,
1724,
273,
9162,
758,
1724,
24899,
9855,
16,
67,
91,
7872,
5157,
63,
77,
19226,
203,
5411,
389,
4963,
273,
389,
4963,
18,
1289,
24899,
323,
1724,
1769,
203,
3639,
289,
203,
203,
203,
3639,
309,
24899,
9561,
13937,
405,
374,
597,
389,
9561,
13937,
411,
12810,
5269,
18049,
9646,
3088,
1283,
13,
288,
203,
5411,
389,
70,
4009,
18352,
273,
389,
70,
4009,
18352,
18,
1289,
24899,
9561,
13937,
1769,
203,
3639,
289,
203,
203,
3639,
327,
389,
4963,
18,
1289,
24899,
70,
4009,
18352,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xd3baaB4890De56c92f52d1B966a7E8d052E26974/sources/localhost/VoxVault.sol | No rebalance implementation for lower fees and faster swaps Get the amount of user shares Calculate percentage of principal being withdrawn Calculate amount of shares to be burned Make sure the user has the required amount in his balance Burn the proportion of shares that are being withdrawn Reduce the amount from user's issued amount Calculate amount of rewards the user has gained Receive the correct proportion of the rewards | function withdraw(uint256 _amount) public {
require(block.number > depositBlocks[msg.sender], 'withdraw: not the same block as deposits');
require(_amount > 0, 'withdraw: positive amount');
require(_amount <= deposits[msg.sender], 'withdraw: more than deposited');
require(issued[msg.sender] > 0, 'withdraw: you need to first make a deposit');
uint256 shares = issued[msg.sender];
uint256 p = (_amount.mul(1e18).div(deposits[msg.sender]));
uint256 r = shares.mul(p).div(1e18);
require(balanceOf(msg.sender) >= r, "withdraw: not enough shares in balance");
_burn(msg.sender, r);
issued[msg.sender] = issued[msg.sender].sub(r);
uint256 rewards = balance().sub(totalDeposited);
uint256 userRewards = 0;
if (rewards > 0) {
userRewards = (rewards.mul(shares)).div(totalSupply());
}
if (userRewards > 0) {
userRewards = userRewards.mul(p).div(1e18);
}
if (b < withdrawAmount) {
uint256 _withdraw = withdrawAmount.sub(b);
IStrategy(strategy).withdraw(_withdraw);
uint256 _after = token.balanceOf(address(this));
uint256 _diff = _after.sub(b);
if (_diff < _withdraw) {
withdrawAmount = b.add(_diff);
}
}
totalDeposited = totalDeposited.sub(_amount);
token.safeTransfer(treasury, _withdrawalFee);
token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee));
emit SharesPurged(msg.sender, r);
emit ClaimRewards(msg.sender, userRewards);
}
| 9,820,443 | [
1,
2279,
283,
12296,
4471,
364,
2612,
1656,
281,
471,
12063,
1352,
6679,
968,
326,
3844,
434,
729,
24123,
9029,
11622,
434,
8897,
3832,
598,
9446,
82,
9029,
3844,
434,
24123,
358,
506,
18305,
329,
4344,
3071,
326,
729,
711,
326,
1931,
3844,
316,
18423,
11013,
605,
321,
326,
23279,
434,
24123,
716,
854,
3832,
598,
9446,
82,
24614,
326,
3844,
628,
729,
1807,
16865,
3844,
9029,
3844,
434,
283,
6397,
326,
729,
711,
314,
8707,
17046,
326,
3434,
23279,
434,
326,
283,
6397,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
12,
11890,
5034,
389,
8949,
13,
1071,
288,
203,
3639,
2583,
12,
2629,
18,
2696,
405,
443,
1724,
6450,
63,
3576,
18,
15330,
6487,
296,
1918,
9446,
30,
486,
326,
1967,
1203,
487,
443,
917,
1282,
8284,
203,
3639,
2583,
24899,
8949,
405,
374,
16,
296,
1918,
9446,
30,
6895,
3844,
8284,
203,
3639,
2583,
24899,
8949,
1648,
443,
917,
1282,
63,
3576,
18,
15330,
6487,
296,
1918,
9446,
30,
1898,
2353,
443,
1724,
329,
8284,
203,
3639,
2583,
12,
1054,
5957,
63,
3576,
18,
15330,
65,
405,
374,
16,
296,
1918,
9446,
30,
1846,
1608,
358,
1122,
1221,
279,
443,
1724,
8284,
203,
203,
3639,
2254,
5034,
24123,
273,
16865,
63,
3576,
18,
15330,
15533,
203,
3639,
2254,
5034,
293,
273,
261,
67,
8949,
18,
16411,
12,
21,
73,
2643,
2934,
2892,
12,
323,
917,
1282,
63,
3576,
18,
15330,
5717,
1769,
203,
3639,
2254,
5034,
436,
273,
24123,
18,
16411,
12,
84,
2934,
2892,
12,
21,
73,
2643,
1769,
203,
203,
3639,
2583,
12,
12296,
951,
12,
3576,
18,
15330,
13,
1545,
436,
16,
315,
1918,
9446,
30,
486,
7304,
24123,
316,
11013,
8863,
203,
3639,
389,
70,
321,
12,
3576,
18,
15330,
16,
436,
1769,
203,
3639,
16865,
63,
3576,
18,
15330,
65,
273,
16865,
63,
3576,
18,
15330,
8009,
1717,
12,
86,
1769,
203,
203,
3639,
2254,
5034,
283,
6397,
273,
11013,
7675,
1717,
12,
4963,
758,
1724,
329,
1769,
203,
3639,
2254,
5034,
729,
17631,
14727,
273,
374,
31,
203,
3639,
309,
261,
266,
6397,
2
] |
./partial_match/56/0xdefac16715671b7b6aeeFE012125f1E19Ee4b7d7/sources/_Token.sol | * @dev Increase the amount of tokens a spender can transfer from the sender's account./ | function increaseAllowance(address spender, uint256 addedValue)
public
isNotFrozen
whenNotPaused
whenUnlocked
returns (bool)
{
expect(spender != address(0), ERROR_INVALID_ADDRESS);
allowed[msg.sender][spender] += addedValue;
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
return true;
}
| 11,212,174 | [
1,
382,
11908,
326,
3844,
434,
2430,
279,
17571,
264,
848,
7412,
628,
326,
5793,
1807,
2236,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
10929,
7009,
1359,
12,
2867,
17571,
264,
16,
2254,
5034,
3096,
620,
13,
203,
565,
1071,
203,
565,
8827,
42,
9808,
203,
565,
1347,
1248,
28590,
203,
565,
1347,
7087,
329,
203,
565,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
4489,
12,
87,
1302,
264,
480,
1758,
12,
20,
3631,
5475,
67,
9347,
67,
15140,
1769,
203,
203,
3639,
2935,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
1011,
3096,
620,
31,
203,
3639,
3626,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
17571,
264,
16,
2935,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
19226,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "../../openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./BridgeToken.sol";
/*
* @title: EvmAssetBank
* @dev: EvmAsset bank which locks Chain33/ERC20 token deposits, and unlocks
* Chain33/ERC20 tokens once the prophecy has been successfully processed.
* @dev:当emv资产转移到go合约时,用于锁定资产;
* 当emv资产从go合约进行提币时,用于解锁资产;
*/
contract EvmAssetBank {
using SafeMath for uint256;
address payable public offlineSave;
uint256 public lockNonce;
mapping(address => uint256) public lockedFunds;
mapping(bytes32 => address) public tokenAllow2Lock;
mapping(address => OfflineSaveCfg) public offlineSaveCfgs;
uint8 public lowThreshold = 5;
uint8 public highThreshold = 80;
struct OfflineSaveCfg {
address token;
string symbol;
uint256 _threshold;
uint8 _percents;
}
/*
* @dev: Event declarations
*/
event LogLock(
address _from,
address _to,
address _token,
string _symbol,
uint256 _value,
uint256 _nonce
);
event LogUnlock(
address _to,
address _token,
string _symbol,
uint256 _value
);
/*
* @dev: Modifier declarations
*/
modifier hasLockedFunds(
address _token,
uint256 _amount
) {
require(
lockedFunds[_token] >= _amount,
"The Bank does not hold enough locked tokens to fulfill this request."
);
_;
}
modifier canDeliver(
address _token,
uint256 _amount
)
{
if(_token == address(0)) {
require(
address(this).balance >= _amount,
'Insufficient Chain33 balance for delivery.'
);
} else {
require(
BridgeToken(_token).balanceOf(address(this)) >= _amount,
'Insufficient ERC20 token balance for delivery.'
);
}
_;
}
modifier availableNonce() {
require(
lockNonce + 1 > lockNonce,
'No available nonces.'
);
_;
}
/*
* @dev: Constructor which sets the lock nonce
*/
constructor()
public
{
lockNonce = 0;
}
/*
* @dev: addToken2AllowLock used to add token with the specified address to be
* allowed locked from GoAsset
*
* @param _token: token contract address
* @param _symbol: token symbol
*/
function addToken2AllowLock(
address _token,
string memory _symbol
)
internal
{
bytes32 symHash = keccak256(abi.encodePacked(_symbol));
address tokenQuery = tokenAllow2Lock[symHash];
require(tokenQuery == address(0), 'The token with the same symbol has been added to lock allow list already.');
tokenAllow2Lock[symHash] = _token;
}
/*
* @dev: addToken2AllowLock used to add token with the specified address to be
* allowed locked from GoAsset
*
* @param _symbol: token symbol
*/
function getLockedTokenAddress(string memory _symbol) public view returns(address)
{
bytes32 symHash = keccak256(abi.encodePacked(_symbol));
return tokenAllow2Lock[symHash];
}
/*
* @dev: configOfflineSave4Lock used to config threshold to trigger tranfer token to offline account
* when the balance of locked token reaches
*
* @param _token: token contract address
* @param _symbol:token symbol,just used for double check that token address and symbol is consistent
* @param _threshold: _threshold to trigger transfer
* @param _percents: amount to transfer per percents of threshold
*/
function configOfflineSave4Lock(
address _token,
string memory _symbol,
uint256 _threshold,
uint8 _percents
)
internal
{
require(
_percents >= lowThreshold && _percents <= highThreshold,
"The percents to trigger should within range [5, 80]"
);
OfflineSaveCfg memory offlineSaveCfg = OfflineSaveCfg(
_token,
_symbol,
_threshold,
_percents
);
offlineSaveCfgs[_token] = offlineSaveCfg;
}
/*
* @dev: getofflineSaveCfg used to get token's offline save configuration
*
* @param _token: token contract address
*/
function getofflineSaveCfg(address _token) public view returns(uint256, uint8)
{
OfflineSaveCfg memory offlineSaveCfg = offlineSaveCfgs[_token];
return (offlineSaveCfg._threshold, offlineSaveCfg._percents);
}
/*
* @dev: Creates a new Chain33 deposit with a unique id.
*
* @param _sender: The sender's Chain33 address.
* @param _recipient: The intended recipient's Chain33 address.
* @param _token: The currency type, either erc20 or Chain33.
* @param _amount: The amount of erc20 tokens/ Chain33 (in wei) to be itemized.
*/
function lockFunds(
address payable _sender,
address _recipient,
address _token,
string memory _symbol,
uint256 _amount
)
internal
{
// Incerment the lock nonce
lockNonce = lockNonce.add(1);
// Increment locked funds by the amount of tokens to be locked
lockedFunds[_token] = lockedFunds[_token].add(_amount);
emit LogLock(
_sender,
_recipient,
_token,
_symbol,
_amount,
lockNonce
);
if (address(0) == offlineSave) {
return;
}
uint256 balance;
if (address(0) == _token) {
balance = address(this).balance;
} else {
balance = BridgeToken(_token).balanceOf(address(this));
}
OfflineSaveCfg memory offlineSaveCfg = offlineSaveCfgs[_token];
//check not zero,so configured already
if (offlineSaveCfg._percents < lowThreshold) {
return;
}
if (balance < offlineSaveCfg._threshold ) {
return;
}
uint256 amount = offlineSaveCfg._percents * balance / 100;
if (address(0) == _token) {
offlineSave.transfer(amount);
} else {
require(BridgeToken(_token).transfer(offlineSave, amount), "Erc20 Token Transfer to offline Save account failed");
}
}
/*
* @dev: Unlocks funds held on contract and sends them to the
* intended recipient
*
* @param _recipient: recipient's Chain33 address
* @param _token: token contract address
* @param _symbol: token symbol
* @param _amount: wei amount or ERC20 token count
*/
function unlockFunds(
address payable _recipient,
address _token,
string memory _symbol,
uint256 _amount
)
internal
{
// Decrement locked funds mapping by the amount of tokens to be unlocked
lockedFunds[_token] = lockedFunds[_token].sub(_amount);
// Transfer funds to intended recipient
if (_token == address(0)) {
_recipient.transfer(_amount);
} else {
require(
BridgeToken(_token).transfer(_recipient, _amount),
"Token transfer failed"
);
}
emit LogUnlock(
_recipient,
_token,
_symbol,
_amount
);
}
}
| @dev: Creates a new Chain33 deposit with a unique id. @param _sender: The sender's Chain33 address. @param _recipient: The intended recipient's Chain33 address. @param _token: The currency type, either erc20 or Chain33. @param _amount: The amount of erc20 tokens/ Chain33 (in wei) to be itemized./ Incerment the lock nonce Increment locked funds by the amount of tokens to be lockedcheck not zero,so configured already | function lockFunds(
address payable _sender,
address _recipient,
address _token,
string memory _symbol,
uint256 _amount
)
internal
{
lockNonce = lockNonce.add(1);
lockedFunds[_token] = lockedFunds[_token].add(_amount);
emit LogLock(
_sender,
_recipient,
_token,
_symbol,
_amount,
lockNonce
);
if (address(0) == offlineSave) {
return;
}
uint256 balance;
if (address(0) == _token) {
balance = address(this).balance;
balance = BridgeToken(_token).balanceOf(address(this));
}
OfflineSaveCfg memory offlineSaveCfg = offlineSaveCfgs[_token];
if (offlineSaveCfg._percents < lowThreshold) {
return;
}
if (balance < offlineSaveCfg._threshold ) {
return;
}
uint256 amount = offlineSaveCfg._percents * balance / 100;
if (address(0) == _token) {
offlineSave.transfer(amount);
require(BridgeToken(_token).transfer(offlineSave, amount), "Erc20 Token Transfer to offline Save account failed");
}
}
| 6,343,959 | [
1,
30,
10210,
279,
394,
7824,
3707,
443,
1724,
598,
279,
3089,
612,
18,
225,
389,
15330,
30,
1021,
5793,
1807,
7824,
3707,
1758,
18,
225,
389,
20367,
30,
1021,
12613,
8027,
1807,
7824,
3707,
1758,
18,
225,
389,
2316,
30,
1021,
5462,
618,
16,
3344,
6445,
71,
3462,
578,
7824,
3707,
18,
225,
389,
8949,
30,
1021,
3844,
434,
6445,
71,
3462,
2430,
19,
7824,
3707,
261,
267,
732,
77,
13,
358,
506,
761,
1235,
18,
19,
657,
2750,
475,
326,
2176,
7448,
17883,
8586,
284,
19156,
635,
326,
3844,
434,
2430,
358,
506,
8586,
1893,
486,
3634,
16,
2048,
4351,
1818,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2176,
42,
19156,
12,
203,
3639,
1758,
8843,
429,
389,
15330,
16,
203,
3639,
1758,
389,
20367,
16,
203,
3639,
1758,
389,
2316,
16,
203,
3639,
533,
3778,
389,
7175,
16,
203,
3639,
2254,
5034,
389,
8949,
203,
565,
262,
203,
3639,
2713,
203,
565,
288,
203,
3639,
2176,
13611,
273,
2176,
13611,
18,
1289,
12,
21,
1769,
203,
540,
203,
3639,
8586,
42,
19156,
63,
67,
2316,
65,
273,
8586,
42,
19156,
63,
67,
2316,
8009,
1289,
24899,
8949,
1769,
203,
203,
540,
3626,
1827,
2531,
12,
203,
5411,
389,
15330,
16,
203,
5411,
389,
20367,
16,
203,
5411,
389,
2316,
16,
203,
5411,
389,
7175,
16,
203,
5411,
389,
8949,
16,
203,
5411,
2176,
13611,
203,
3639,
11272,
203,
203,
3639,
309,
261,
2867,
12,
20,
13,
422,
13493,
4755,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
11013,
31,
203,
3639,
309,
261,
2867,
12,
20,
13,
422,
389,
2316,
13,
288,
203,
5411,
11013,
273,
1758,
12,
2211,
2934,
12296,
31,
203,
5411,
11013,
273,
24219,
1345,
24899,
2316,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
289,
203,
203,
3639,
29708,
4755,
8198,
3778,
13493,
4755,
8198,
273,
13493,
4755,
39,
74,
564,
63,
67,
2316,
15533,
203,
3639,
309,
261,
23787,
4755,
8198,
6315,
8849,
87,
411,
4587,
7614,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
309,
261,
12296,
411,
13493,
4755,
8198,
6315,
8699,
262,
288,
203,
5411,
327,
31,
203,
3639,
289,
2
] |
./full_match/10200/0x34E520dc1d2Db660113b64724e14CEdCD01Ee879/sources/src/kleros-v1/kleros-liquid-xdai/WrappedPinakion.sol | * @notice Converts wrapped PNK back into PNK using the Token Bridge. @dev This function is not strictly needed, but it provides a good UX to users who want to get their Mainnet's PNK back. What normally takes 3 transactions, here is done in one go. Notice that the PNK have to be claimed on Mainnet's TokenBridge by the receiver. @param _amount The amount of PNK to withdraw. @param _receiver The address which will receive the PNK back in the foreign chain./ Using approve is safe here, because this contract approves the bridge to spend the tokens and triggers the relay immediately. | function withdrawAndConvertToPNK(uint256 _amount, address _receiver) external {
_burn(_amount);
xPinakion.approve(address(tokenBridge), _amount);
tokenBridge.relayTokens(xPinakion, _receiver, _amount);
}
| 3,784,908 | [
1,
5692,
5805,
453,
50,
47,
1473,
1368,
453,
50,
47,
1450,
326,
3155,
24219,
18,
225,
1220,
445,
353,
486,
23457,
3577,
16,
1496,
518,
8121,
279,
7494,
587,
60,
358,
3677,
10354,
2545,
358,
336,
3675,
12740,
2758,
1807,
453,
50,
47,
1473,
18,
18734,
15849,
5530,
890,
8938,
16,
2674,
353,
2731,
316,
1245,
1960,
18,
24914,
716,
326,
453,
50,
47,
1240,
358,
506,
7516,
329,
603,
12740,
2758,
1807,
3155,
13691,
635,
326,
5971,
18,
225,
389,
8949,
1021,
3844,
434,
453,
50,
47,
358,
598,
9446,
18,
225,
389,
24454,
1021,
1758,
1492,
903,
6798,
326,
453,
50,
47,
1473,
316,
326,
5523,
2687,
18,
19,
11637,
6617,
537,
353,
4183,
2674,
16,
2724,
333,
6835,
6617,
3324,
326,
10105,
358,
17571,
326,
2430,
471,
11752,
326,
18874,
7636,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
1876,
2723,
774,
15124,
47,
12,
11890,
5034,
389,
8949,
16,
1758,
389,
24454,
13,
3903,
288,
203,
3639,
389,
70,
321,
24899,
8949,
1769,
203,
3639,
619,
12178,
581,
285,
18,
12908,
537,
12,
2867,
12,
2316,
13691,
3631,
389,
8949,
1769,
203,
3639,
1147,
13691,
18,
2878,
528,
5157,
12,
92,
12178,
581,
285,
16,
389,
24454,
16,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xEb5302954d013483091C5725d5d3Abe5A703A464/sources/src/SellerFinancing.sol | approve the NFT for Seaport conduit decode seaport order data validate order instantiate weth calculate totalConsiderationAmount execute sale on Seaport check amount received is more than minSaleAmount | function _sellAsset(
address nftContractAddress,
uint256 nftId,
uint256 minSaleAmount,
bytes calldata data
) private returns (uint256 saleAmountReceived) {
IERC721Upgradeable(nftContractAddress).approve(seaportContractAddress, nftId);
ISeaport.Order memory order = abi.decode(data, (ISeaport.Order));
_validateSaleOrder(order, nftContractAddress, nftId);
IERC20Upgradeable asset = IERC20Upgradeable(wethContractAddress);
uint256 totalConsiderationAmount;
for (uint256 i = 1; i < order.parameters.totalOriginalConsiderationItems; i++) {
totalConsiderationAmount += order.parameters.consideration[i].endAmount;
}
if (!ISeaport(seaportContractAddress).fulfillOrder(order, bytes32(0))) {
revert SeaportOrderNotFulfilled();
}
abi.encodeWithSignature(
"withdraw(uint256)",
order.parameters.offer[0].endAmount - totalConsiderationAmount
)
);
if (!success) {
revert WethConversionFailed();
}
if (saleAmountReceived < minSaleAmount) {
revert InsufficientAmountReceivedFromSale(saleAmountReceived, minSaleAmount);
}
}
| 16,059,711 | [
1,
12908,
537,
326,
423,
4464,
364,
3265,
438,
499,
356,
2544,
305,
2495,
695,
438,
499,
1353,
501,
1954,
1353,
10275,
341,
546,
4604,
2078,
9054,
3585,
367,
6275,
1836,
272,
5349,
603,
3265,
438,
499,
866,
3844,
5079,
353,
1898,
2353,
1131,
30746,
6275,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
87,
1165,
6672,
12,
203,
3639,
1758,
290,
1222,
8924,
1887,
16,
203,
3639,
2254,
5034,
290,
1222,
548,
16,
203,
3639,
2254,
5034,
1131,
30746,
6275,
16,
203,
3639,
1731,
745,
892,
501,
203,
565,
262,
3238,
1135,
261,
11890,
5034,
272,
5349,
6275,
8872,
13,
288,
203,
3639,
467,
654,
39,
27,
5340,
10784,
429,
12,
82,
1222,
8924,
1887,
2934,
12908,
537,
12,
307,
438,
499,
8924,
1887,
16,
290,
1222,
548,
1769,
203,
203,
3639,
467,
1761,
438,
499,
18,
2448,
3778,
1353,
273,
24126,
18,
3922,
12,
892,
16,
261,
45,
1761,
438,
499,
18,
2448,
10019,
203,
203,
3639,
389,
5662,
30746,
2448,
12,
1019,
16,
290,
1222,
8924,
1887,
16,
290,
1222,
548,
1769,
203,
203,
3639,
467,
654,
39,
3462,
10784,
429,
3310,
273,
467,
654,
39,
3462,
10784,
429,
12,
91,
546,
8924,
1887,
1769,
203,
203,
3639,
2254,
5034,
2078,
9054,
3585,
367,
6275,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
404,
31,
277,
411,
1353,
18,
3977,
18,
4963,
8176,
9054,
3585,
367,
3126,
31,
277,
27245,
288,
203,
5411,
2078,
9054,
3585,
367,
6275,
1011,
1353,
18,
3977,
18,
8559,
3585,
367,
63,
77,
8009,
409,
6275,
31,
203,
3639,
289,
203,
203,
203,
203,
3639,
309,
16051,
45,
1761,
438,
499,
12,
307,
438,
499,
8924,
1887,
2934,
2706,
5935,
2448,
12,
1019,
16,
1731,
1578,
12,
20,
20349,
288,
203,
5411,
15226,
3265,
438,
499,
2448,
1248,
23747,
13968,
5621,
203,
3639,
289,
203,
203,
2
] |
./full_match/1/0xE292B17018189aDAc3321E95494520F35859b9df/sources/contracts/pool/DittoPoolMarketMake.sol | @inheritdoc IDittoPool | function addLiquidity(
uint256 lpId_,
uint256[] calldata nftIdList_,
uint256 tokenDepositAmount_,
bytes calldata permitterData_,
bytes calldata referrer_
) external nonReentrant {
if(_isPrivatePool){
_onlyOwner();
if(_privatePoolOwnerLpId != lpId_){
revert DittoPoolMarketMakeOneLpPerPrivatePool();
}
}
if (tokenDepositAmount_ == 0 && nftIdList_.length == 0) {
revert DittoPoolMarketMakeMustDepositLiquidity();
}
if (address(_lpNft.getPoolForLpId(lpId_)) != address(this)) {
revert DittoPoolMarketMakeWrongPoolForLpId();
}
_transferInLiquidity(lpId_, nftIdList_, tokenDepositAmount_, permitterData_);
emit DittoPoolMarketMakeLiquidityAdded(msg.sender, lpId_, nftIdList_, tokenDepositAmount_, referrer_);
}
| 16,497,029 | [
1,
36,
10093,
1599,
305,
869,
2864,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
48,
18988,
24237,
12,
203,
3639,
2254,
5034,
12423,
548,
67,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
290,
1222,
22117,
67,
16,
203,
3639,
2254,
5034,
1147,
758,
1724,
6275,
67,
16,
203,
3639,
1731,
745,
892,
4641,
6132,
751,
67,
16,
203,
3639,
1731,
745,
892,
14502,
67,
203,
565,
262,
3903,
1661,
426,
8230,
970,
288,
203,
3639,
309,
24899,
291,
6014,
2864,
15329,
203,
5411,
389,
3700,
5541,
5621,
203,
5411,
309,
24899,
1152,
2864,
5541,
48,
84,
548,
480,
12423,
548,
67,
15329,
203,
7734,
15226,
463,
305,
869,
2864,
3882,
278,
6464,
3335,
48,
84,
2173,
6014,
2864,
5621,
203,
5411,
289,
203,
3639,
289,
203,
3639,
309,
261,
2316,
758,
1724,
6275,
67,
422,
374,
597,
290,
1222,
22117,
27799,
2469,
422,
374,
13,
288,
203,
5411,
15226,
463,
305,
869,
2864,
3882,
278,
6464,
10136,
758,
1724,
48,
18988,
24237,
5621,
203,
3639,
289,
203,
3639,
309,
261,
2867,
24899,
9953,
50,
1222,
18,
588,
2864,
1290,
48,
84,
548,
12,
9953,
548,
67,
3719,
480,
1758,
12,
2211,
3719,
288,
203,
5411,
15226,
463,
305,
869,
2864,
3882,
278,
6464,
13634,
2864,
1290,
48,
84,
548,
5621,
203,
3639,
289,
203,
3639,
389,
13866,
382,
48,
18988,
24237,
12,
9953,
548,
67,
16,
290,
1222,
22117,
67,
16,
1147,
758,
1724,
6275,
67,
16,
4641,
6132,
751,
67,
1769,
203,
203,
3639,
3626,
463,
305,
869,
2864,
3882,
278,
6464,
48,
18988,
24237,
8602,
12,
3576,
18,
15330,
16,
12423,
548,
2
] |
./partial_match/3/0x76B120B6DF363189d07542Bf4f7059c81eB54E1c/sources/PigeonMasterFarmer.sol | Withdraw LP tokens from PigeonMasterFarmer. | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "PigeonMasterFarmer::withdraw: not good");
updatePool(_pid);
_harvest(_pid);
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accPigeonPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
| 5,234,605 | [
1,
1190,
9446,
511,
52,
2430,
628,
453,
360,
73,
265,
7786,
42,
4610,
264,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
13,
1071,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
3576,
18,
15330,
15533,
203,
3639,
2583,
12,
1355,
18,
8949,
1545,
389,
8949,
16,
315,
52,
360,
73,
265,
7786,
42,
4610,
264,
2866,
1918,
9446,
30,
486,
7494,
8863,
203,
203,
3639,
1089,
2864,
24899,
6610,
1769,
203,
3639,
389,
30250,
26923,
24899,
6610,
1769,
203,
203,
3639,
309,
24899,
8949,
405,
374,
13,
288,
203,
5411,
729,
18,
8949,
273,
729,
18,
8949,
18,
1717,
24899,
8949,
1769,
203,
5411,
2845,
18,
9953,
1345,
18,
4626,
5912,
12,
2867,
12,
3576,
18,
15330,
3631,
389,
8949,
1769,
203,
3639,
289,
203,
3639,
729,
18,
266,
2913,
758,
23602,
273,
729,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
52,
360,
73,
265,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
1769,
203,
3639,
3626,
3423,
9446,
12,
3576,
18,
15330,
16,
389,
6610,
16,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xCc2A55361183cf2B623477C55d82B7E73dF8e7c9/sources/contracts/Swapper.sol | @notice Owner can set Uniswap V2 Router @param _router Router address to add | function setRouter(address _router) external onlyOwner {
uniswapV2Router = IUniswapV2Router02(_router);
}
| 3,866,539 | [
1,
5541,
848,
444,
1351,
291,
91,
438,
776,
22,
9703,
225,
389,
10717,
9703,
1758,
358,
527,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
444,
8259,
12,
2867,
389,
10717,
13,
3903,
1338,
5541,
288,
203,
565,
640,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
24899,
10717,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xd8Fd88b5BBbA4b7724C95E6e1A700613CbBB39f3/sources/contracts/Storage.sol | Unlock Required Key Counter for Branches
| uint8 keys; | 839,217 | [
1,
7087,
10647,
1929,
9354,
364,
15449,
281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
28,
1311,
31,
2868,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2021 Project Galaxy.
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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.7.6;
//import "SafeMath.sol";
//import "Address.sol";
import "ERC1155.sol";
import "Ownable.sol";
import "IStarNFT.sol";
/**
* based on https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/ERC1155.sol
*/
contract StarNFTV1 is ERC1155, IStarNFT, Ownable {
using SafeMath for uint256;
// using Address for address;
// using ERC165Checker for address;
/* ============ Events ============ */
event EventMinterAdded(address indexed newMinter);
event EventMinterRemoved(address indexed oldMinter);
/* ============ Modifiers ============ */
/**
* Only minter.
*/
modifier onlyMinter() {
require(minters[msg.sender], "must be minter");
_;
}
/* ============ Enums ================ */
/* ============ Structs ============ */
/* ============ State Variables ============ */
// Used as the URI for all token types by ID substitution, e.g. https://galaxy.eco/{address}/{id}.json
string public baseURI;
// Mint and burn star.
mapping(address => bool) public minters;
// Total star count, including burnt nft
uint256 public starCount;
/* ============ Constructor ============ */
constructor () ERC1155("") {}
/* ============ External Functions ============ */
function mint(address account, uint256 powah) external onlyMinter override returns (uint256) {
starCount++;
uint256 sID = starCount;
_mint(account, sID, 1, "");
return sID;
}
function mintBatch(address account, uint256 amount, uint256[] calldata powahArr) external onlyMinter override returns (uint256[] memory) {
uint256[] memory ids = new uint256[](amount);
uint256[] memory amounts = new uint256[](amount);
for (uint i = 0; i < ids.length; i++) {
starCount++;
ids[i] = starCount;
amounts[i] = 1;
}
_mintBatch(account, ids, amounts, "");
return ids;
}
function burn(address account, uint256 id) external onlyMinter override {
require(isApprovedForAll(account, _msgSender()), "ERC1155: caller is not approved");
_burn(account, id, 1);
}
function burnBatch(address account, uint256[] calldata ids) external onlyMinter override {
require(isApprovedForAll(account, _msgSender()), "ERC1155: caller is not approved");
uint256[] memory amounts = new uint256[](ids.length);
for (uint i = 0; i < ids.length; i++) {
amounts[i] = 1;
}
_burnBatch(account, ids, amounts);
}
/**
* PRIVILEGED MODULE FUNCTION. Sets a new baseURI for all token types.
*/
function setURI(string memory newURI) external onlyOwner {
baseURI = newURI;
}
/**
* PRIVILEGED MODULE FUNCTION. Add a new minter.
*/
function addMinter(address minter) external onlyOwner {
require(minter != address(0), "Minter must not be null address");
require(!minters[minter], "Minter already added");
minters[minter] = true;
emit EventMinterAdded(minter);
}
/**
* PRIVILEGED MODULE FUNCTION. Remove a old minter.
*/
function removeMinter(address minter) external onlyOwner {
require(minters[minter], "Minter does not exist");
delete minters[minter];
emit EventMinterRemoved(minter);
}
/* ============ External Getter Functions ============ */
/**
* See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256 id) external view override returns (string memory) {
require(id <= starCount, "NFT does not exist");
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(baseURI).length == 0) {
return "";
} else {
// bytes memory b = new bytes(32);
// assembly { mstore(add(b, 32), id) }
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(baseURI, uint2str(id), ".json"));
}
}
/**
* Is the nft owner.
* Requirements:
* - `account` must not be zero address.
*/
function isOwnerOf(address account, uint256 id) public view override returns (bool) {
return balanceOf(account, id) == 1;
}
function getNumMinted() external view override returns (uint256) {
return starCount;
}
/* ============ Internal Functions ============ */
/* ============ Private Functions ============ */
/* ============ Util Functions ============ */
function uint2str(uint _i) internal pure returns (string memory) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bStr = new bytes(len);
uint k = len;
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.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "IERC1155.sol";
import "IERC1155MetadataURI.sol";
import "IERC1155Receiver.sol";
import "Context.sol";
import "ERC165.sol";
import "SafeMath.sol";
import "Address.sol";
/**
*
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address for address;
// Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor (string memory uri_) public {
_setURI(uri_);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) external view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
{ }
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "IERC165.sol";
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/*
Copyright 2021 Project Galaxy.
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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.7.6;
/**
* @title IStarNFT
* @author Galaxy Protocol
*
* Interface for operating with StarNFTs.
*/
interface IStarNFT {
/* ============ Events =============== */
/* ============ Functions ============ */
function isOwnerOf(address, uint256) external view returns (bool);
function getNumMinted() external view returns (uint256);
// mint
function mint(address account, uint256 powah) external returns (uint256);
function mintBatch(address account, uint256 amount, uint256[] calldata powahArr) external returns (uint256[] memory);
function burn(address account, uint256 id) external;
function burnBatch(address account, uint256[] calldata ids) external;
} | * PRIVILEGED MODULE FUNCTION. Sets a new baseURI for all token types./ | function setURI(string memory newURI) external onlyOwner {
baseURI = newURI;
}
| 589,537 | [
1,
7698,
4136,
19384,
2056,
14057,
13690,
18,
11511,
279,
394,
1026,
3098,
364,
777,
1147,
1953,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
3098,
12,
1080,
3778,
394,
3098,
13,
3903,
1338,
5541,
288,
203,
3639,
1026,
3098,
273,
394,
3098,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xAdcDAEc4fD335CC9A42a520b434585F343202A57/sources/MarginPoolAddressesProvider.sol | * @dev Internal function to update the implementation of a specific proxied component of the protocol - If there is no proxy registered in the given `id`, it creates the proxy setting `newAdress` as implementation and calls the initialize() function on the proxy - If there is already a proxy registered, it just updates the implementation to `newAddress` and calls the initialize() function via upgradeToAndCall() in the proxy @param id The id of the proxy to be updated @param newAddress The address of the new implementation/ | function _updatePoolImpl(bytes32 id, address newAddress, address UniswapRouter, address SushiswapRouter,address _weth) internal {
address payable proxyAddress = payable(_addresses[id]);
InitializableImmutableAdminUpgradeabilityProxy proxy =
InitializableImmutableAdminUpgradeabilityProxy(proxyAddress);
bytes memory params = abi.encodeWithSignature('initialize(address,address,address,address)', address(this), UniswapRouter,SushiswapRouter, _weth);
if (proxyAddress == address(0)) {
proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this));
proxy.initialize(newAddress, params);
_addresses[id] = address(proxy);
emit ProxyCreated(id, address(proxy));
proxy.upgradeToAndCall(newAddress, params);
}
}
| 16,561,501 | [
1,
3061,
445,
358,
1089,
326,
4471,
434,
279,
2923,
21875,
1794,
434,
326,
1771,
300,
971,
1915,
353,
1158,
2889,
4104,
316,
326,
864,
1375,
350,
9191,
518,
3414,
326,
2889,
3637,
1375,
2704,
1871,
663,
68,
282,
487,
4471,
471,
4097,
326,
4046,
1435,
445,
603,
326,
2889,
300,
971,
1915,
353,
1818,
279,
2889,
4104,
16,
518,
2537,
4533,
326,
4471,
358,
1375,
2704,
1887,
68,
471,
282,
4097,
326,
4046,
1435,
445,
3970,
8400,
774,
1876,
1477,
1435,
316,
326,
2889,
225,
612,
1021,
612,
434,
326,
2889,
358,
506,
3526,
225,
394,
1887,
1021,
1758,
434,
326,
394,
4471,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
2725,
2864,
2828,
12,
3890,
1578,
612,
16,
1758,
394,
1887,
16,
1758,
1351,
291,
91,
438,
8259,
16,
1758,
348,
1218,
291,
91,
438,
8259,
16,
2867,
389,
91,
546,
13,
2713,
288,
203,
565,
1758,
8843,
429,
2889,
1887,
273,
8843,
429,
24899,
13277,
63,
350,
19226,
203,
203,
565,
10188,
6934,
16014,
4446,
10784,
2967,
3886,
2889,
273,
203,
1377,
10188,
6934,
16014,
4446,
10784,
2967,
3886,
12,
5656,
1887,
1769,
203,
565,
1731,
3778,
859,
273,
24126,
18,
3015,
1190,
5374,
2668,
11160,
12,
2867,
16,
2867,
16,
2867,
16,
2867,
13,
2187,
1758,
12,
2211,
3631,
1351,
291,
91,
438,
8259,
16,
55,
1218,
291,
91,
438,
8259,
16,
389,
91,
546,
1769,
203,
203,
565,
309,
261,
5656,
1887,
422,
1758,
12,
20,
3719,
288,
203,
1377,
2889,
273,
394,
10188,
6934,
16014,
4446,
10784,
2967,
3886,
12,
2867,
12,
2211,
10019,
203,
1377,
2889,
18,
11160,
12,
2704,
1887,
16,
859,
1769,
203,
1377,
389,
13277,
63,
350,
65,
273,
1758,
12,
5656,
1769,
203,
1377,
3626,
7659,
6119,
12,
350,
16,
1758,
12,
5656,
10019,
203,
1377,
2889,
18,
15097,
774,
1876,
1477,
12,
2704,
1887,
16,
859,
1769,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.7.6;
/**
* Users can buy, sell and transfer tokens using the respective functions.
* When users buy, they must upload multiples of 1 Gwei (token price), or lose the excess funds.
* If you sell your tokens, you are given their value and they are removed from the overall supply.
* totalSupply is the number of tokens available for purchase, initialSupply is the minted totalSupply
* To find your token balance, use getBalance with your wallet adddress.
**/
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/math/SafeMath.sol";
contract newToken {
using SafeMath for uint256;
//Variables
uint256 public tokenPrice;
uint256 private totalSupply; //total token pool remaining
uint256 public initialSupply; //total tokens minted
uint256 private burntTokens;
address private owner; //person who deployed contract
string public symbol; //simple symbol of currency
//Private Variables
address private buyer; //buyers address
uint256 private amount; //number of tokens, not wei!
bool private successBuy; //flag to show if a buy has happened
//Mappings
mapping(address => uint256) balance; //tokens owned by each user
//Events
event Purchase(address indexed buyer, uint256 amount);
event Transfer(address indexed sender, address indexed receiver, uint256 amount);
event Sell(address indexed seller, uint256 amount);
event Price(uint256 price);
constructor() public {
assert(1 ether == 1e18);
tokenPrice = 1e9; // price 1Gwei arbitrarily
owner = msg.sender; //owner is the person who deploys contract on network
symbol = "MT";
initialSupply = 1000; //arbitrarily set total supply to 1000 - contract raises total 1ETH
burntTokens = 0; //total tokens taken out of circulation by sales
totalSupply = initialSupply; //number available to buy is total minted at the beginning.
}
function buyToken(uint256 _amount) public payable returns(bool success){
require(msg.value >= tokenPrice.mul(_amount), "You dont have enough ETH to buy this many tokens.");
require(_amount > 0, "you must buy >0 tokens!");
balance[msg.sender] += _amount; // add tokens to owner balance
totalSupply = totalSupply.sub(_amount); //remove these from total supply
emit Purchase(msg.sender,amount); // add this to ledger (mapping)
successBuy = true;
return true;
}
function transfer(address _recipient, uint256 _amount) public payable returns(bool){
require(_recipient != address(0), "You cannot sent to the zero address." );
require(balance[msg.sender] >= _amount, "Your token balance is too low.");
require(_recipient != msg.sender, "You cannot transfer tokens to yourself.");
balance[msg.sender] = balance[msg.sender].sub(_amount);
balance[_recipient] = balance[_recipient].add(_amount);
emit Transfer(msg.sender, _recipient, _amount);
return true;
}
function sellToken(uint256 _amount) public payable returns(bool){
require(balance[msg.sender] >= _amount, "You dont have enough tokens to sell this amount.");
require(_amount > 0, "you must sell >0 tokens!");
balance[msg.sender] = balance[msg.sender].sub(_amount); // remove amount from balance
// totalSupply = totalSupply.add(_amount); //return tokens to totalSupply
// burn tokens by not returning them to total supply
burntTokens += _amount;
msg.sender.transfer(tokenPrice.mul(_amount)); //pay person for their token return
emit Sell(msg.sender, _amount);
return true;
}
// allow the token price to be changed by owner only - this is arbitrary but can be doubled easily
function changePrice(uint256 price) payable public returns(bool){
require(msg.sender == owner, "Only the owner can change price.");
require(successBuy == true,'No tokens have yet been bought. Cannot change price.');
// total outstanding tokens = total minted - totalsold - burntTokens
require(((msg.value + contractBalance()) >= price.mul(initialSupply-totalSupply-burntTokens)),
'Not enough funds to change price.');
tokenPrice = price;
//priceChange += 1; //counter of how many times price has changed
return true;
}
//a view that returns the amount of tokens that the user owns
function getBalance(address _user) public view returns(uint256){
return(balance[_user]);
}
function contractBalance() public view returns(uint256){
require(msg.sender == owner, "Owner only can view contract balance");
return address(this).balance;
}
}
| totalSupply = totalSupply.add(_amount); return tokens to totalSupply burn tokens by not returning them to total supply | function sellToken(uint256 _amount) public payable returns(bool){
require(balance[msg.sender] >= _amount, "You dont have enough tokens to sell this amount.");
require(_amount > 0, "you must sell >0 tokens!");
burntTokens += _amount;
emit Sell(msg.sender, _amount);
return true;
}
| 5,409,446 | [
1,
4963,
3088,
1283,
273,
2078,
3088,
1283,
18,
1289,
24899,
8949,
1769,
327,
2430,
358,
2078,
3088,
1283,
18305,
2430,
635,
486,
5785,
2182,
358,
2078,
14467,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
357,
80,
1345,
12,
11890,
5034,
389,
8949,
13,
1071,
8843,
429,
1135,
12,
6430,
15329,
203,
3639,
2583,
12,
12296,
63,
3576,
18,
15330,
65,
1545,
389,
8949,
16,
315,
6225,
14046,
1240,
7304,
2430,
358,
357,
80,
333,
3844,
1199,
1769,
203,
3639,
2583,
24899,
8949,
405,
374,
16,
315,
19940,
1297,
357,
80,
405,
20,
2430,
4442,
1769,
203,
540,
203,
3639,
18305,
88,
5157,
1011,
389,
8949,
31,
7010,
540,
203,
3639,
3626,
348,
1165,
12,
3576,
18,
15330,
16,
389,
8949,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(now > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// Contract implementation
contract BabyMongoose is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'BabyMongoose';
string private _symbol = 'BBMG';
uint8 private _decimals = 9;
uint256 private _taxFee = 10;
uint256 private _teamFee = 10;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousTeamFee = _teamFee;
address payable public _devWalletAddress;
address payable public _marketingWalletAddress;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwap = false;
bool public swapEnabled = true;
uint256 private _maxTxAmount = 100000000000000e9;
// We will set a minimum amount of tokens to be swaped => 5M
uint256 private _numOfTokensToExchangeForTeam = 5 * 10**3 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable devWalletAddress, address payable marketingWalletAddress) public {
_devWalletAddress = devWalletAddress;
_marketingWalletAddress = marketingWalletAddress;
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
// Exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function removeAllFee() private {
if(_taxFee == 0 && _teamFee == 0) return;
_previousTaxFee = _taxFee;
_previousTeamFee = _teamFee;
_taxFee = 0;
_teamFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_teamFee = _previousTeamFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap?
// also, don't get caught in a circular team event.
// also, don't swap if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
// We need to swap the current tokens to ETH and send to the team wallet
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
//transfer amount, it will take tax and team fee
_tokenTransfer(sender,recipient,amount,takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{
// 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 sendETHToTeam(uint256 amount) private {
_devWalletAddress.transfer(amount.div(2));
_marketingWalletAddress.transfer(amount.div(2));
}
// We are exposing these functions to be able to manual swap and send
// in case the token is highly valued and 5M becomes too much
function manualSwap() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external onlyOwner() {
uint256 contractETHBalance = address(this).balance;
sendETHToTeam(contractETHBalance);
}
function setSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 teamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(teamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getTaxFee() private view returns(uint256) {
return _taxFee;
}
function _getMaxTxAmount() private view returns(uint256) {
return _maxTxAmount;
}
function _getETHBalance() public view returns(uint256 balance) {
return address(this).balance;
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
require(taxFee >= 1 && taxFee <= 25, 'taxFee should be in 1 - 25');
_taxFee = taxFee;
}
function _setTeamFee(uint256 teamFee) external onlyOwner() {
require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25');
_teamFee = teamFee;
}
function _setLDWallet(address payable devWalletAddress) external onlyOwner() {
_devWalletAddress = devWalletAddress;
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
require(maxTxAmount >= 100000000000000e9 , 'maxTxAmount should be greater than 100000000000000e9');
_maxTxAmount = maxTxAmount;
}
} | Contract implementation We will set a minimum amount of tokens to be swaped => 5M | contract BabyMongoose is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'BabyMongoose';
string private _symbol = 'BBMG';
uint8 private _decimals = 9;
uint256 private _taxFee = 10;
uint256 private _teamFee = 10;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousTeamFee = _teamFee;
address payable public _devWalletAddress;
address payable public _marketingWalletAddress;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwap = false;
bool public swapEnabled = true;
uint256 private _maxTxAmount = 100000000000000e9;
uint256 private _numOfTokensToExchangeForTeam = 5 * 10**3 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable devWalletAddress, address payable marketingWalletAddress) public {
_devWalletAddress = devWalletAddress;
_marketingWalletAddress = marketingWalletAddress;
_rOwned[_msgSender()] = _rTotal;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
} else {
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function removeAllFee() private {
if(_taxFee == 0 && _teamFee == 0) return;
_previousTaxFee = _taxFee;
_previousTeamFee = _teamFee;
_taxFee = 0;
_teamFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_teamFee = _previousTeamFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
bool takeFee = true;
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
_tokenTransfer(sender,recipient,amount,takeFee);
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function sendETHToTeam(uint256 amount) private {
_devWalletAddress.transfer(amount.div(2));
_marketingWalletAddress.transfer(amount.div(2));
}
function manualSwap() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external onlyOwner() {
uint256 contractETHBalance = address(this).balance;
sendETHToTeam(contractETHBalance);
}
function setSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if(!takeFee)
removeAllFee();
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();
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if(!takeFee)
removeAllFee();
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();
}
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
} else {
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 teamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(teamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getTaxFee() private view returns(uint256) {
return _taxFee;
}
function _getMaxTxAmount() private view returns(uint256) {
return _maxTxAmount;
}
function _getETHBalance() public view returns(uint256 balance) {
return address(this).balance;
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
require(taxFee >= 1 && taxFee <= 25, 'taxFee should be in 1 - 25');
_taxFee = taxFee;
}
function _setTeamFee(uint256 teamFee) external onlyOwner() {
require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25');
_teamFee = teamFee;
}
function _setLDWallet(address payable devWalletAddress) external onlyOwner() {
_devWalletAddress = devWalletAddress;
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
require(maxTxAmount >= 100000000000000e9 , 'maxTxAmount should be greater than 100000000000000e9');
_maxTxAmount = maxTxAmount;
}
} | 1,365,210 | [
1,
8924,
4471,
1660,
903,
444,
279,
5224,
3844,
434,
2430,
358,
506,
1352,
5994,
516,
1381,
49,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
6835,
605,
24383,
16578,
2584,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
3639,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
3639,
1450,
5267,
364,
1758,
31,
203,
203,
3639,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
3639,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
3639,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
3639,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
203,
3639,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
31,
203,
3639,
1758,
8526,
3238,
389,
24602,
31,
203,
203,
3639,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
3639,
2254,
5034,
3238,
389,
88,
5269,
273,
15088,
9449,
380,
1728,
636,
29,
31,
203,
3639,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
3639,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
203,
3639,
533,
3238,
389,
529,
273,
296,
38,
24383,
16578,
2584,
13506,
203,
3639,
533,
3238,
389,
7175,
273,
296,
9676,
49,
43,
13506,
203,
3639,
2254,
28,
3238,
389,
31734,
273,
2468,
31,
203,
203,
3639,
2254,
5034,
3238,
389,
8066,
14667,
273,
1728,
31,
203,
3639,
2254,
5034,
3238,
389,
10035,
14667,
273,
1728,
31,
203,
3639,
2254,
5034,
3238,
389,
11515,
7731,
14667,
273,
389,
8066,
14667,
31,
203,
2
] |
./partial_match/80001/0x636C4701Fdd1C46e47177cef7032b26402Bf7251/sources/minter1.sol | * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation./ | function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
| 8,818,664 | [
1,
5692,
392,
1375,
2867,
68,
598,
5499,
769,
434,
4200,
1731,
358,
2097,
486,
6697,
2937,
11768,
1375,
1080,
68,
20070,
4335,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
445,
18272,
12,
2867,
3091,
13,
2713,
16618,
1135,
261,
1080,
3778,
13,
288,
203,
5411,
327,
18272,
12,
11890,
5034,
12,
11890,
16874,
12,
4793,
13,
3631,
389,
15140,
67,
7096,
1769,
203,
3639,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
This file is part of The Colony Network.
The Colony Network is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The Colony Network 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 The Colony Network. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.4.23;
pragma experimental "v0.5.0";
import "../lib/dappsys/math.sol";
import "./IColonyNetwork.sol";
import "./PatriciaTree/PatriciaTreeProofs.sol";
// TODO: Can we handle all possible disputes regarding the very first hash that should be set?
// Currently, at the very least, we can't handle a dispute if the very first entry is disputed.
// A possible workaround would be to 'kick off' reputation mining with a known dummy state...
contract ReputationMiningCycle is PatriciaTreeProofs, DSMath {
ReputationLogEntry[] reputationUpdateLog;
struct ReputationLogEntry {
address user;
int amount;
uint256 skillId;
address colony;
uint256 nUpdates;
uint256 nPreviousUpdates;
}
address colonyNetworkAddress;
// TODO: Do we need both these mappings?
mapping (bytes32 => mapping( uint256 => address[])) public submittedHashes;
mapping (address => Submission) public reputationHashSubmissions;
uint256 public reputationMiningWindowOpenTimestamp;
mapping (uint256 => Submission[]) public disputeRounds;
// Tracks the number of submissions in each round that have completed their challenge, one way or the other.
// This might be that they passed the challenge, it might be that their opponent passed (and therefore by implication,
// they failed), or it might be that they timed out
mapping (uint256 => uint256) nHashesCompletedChallengeRound;
// A flaw with this is that if someone spams lots of nonsense transactions, then 'good' users still have to come along and
// explicitly complete the pairings. But if they get the tokens that were staked in order to make the submission, maybe
// that's okay...?
// Number of unique hashes submitted
uint256 public nSubmittedHashes = 0;
uint256 public nInvalidatedHashes = 0;
struct Submission {
bytes32 proposedNewRootHash; // The hash that the submitter is proposing as the next reputation hash
uint256 nNodes; // The number of nodes in the reputation tree being proposed as the next reputation hash
uint256 lastResponseTimestamp; // If nonzero, the last time that a valid response was received corresponding to this
// submission during the challenge process - either binary searching for the challenge,
// responding to the challenge itself or submitting the JRH
uint256 challengeStepCompleted; // How many valid responses have been received corresponding to this submission during
// the challenge process.
bytes32 jrh; // The Justification Root Hash corresponding to this submission.
bytes32 intermediateReputationHash; // The hash this submission hash has as a leaf node in the tree the JRH is the root of where
// this submission and its opponent differ for the first time.
uint256 intermediateReputationNNodes; // The number of nodes in the reputation tree in the reputation state where this submission and
// its opponent first differ.
uint256 jrhNnodes; // The number of nodes in the tree the JRH is the root of.
uint256 lowerBound; // During the binary search, the lowest index in the justification tree that might still be the
// first place where the two submissions differ.
uint256 upperBound; // During the binary search, the highest index in the justification tree that might still be the
// first place where the two submissions differ.
// When the binary search is complete, lowerBound and upperBound are equal
uint256 provedPreviousReputationUID; // If the disagreement between this submission and its opponent is related to the insertion of a
// new leaf, the submitters also submit proof of a reputation in a state that the two agree on. The
// UID that reputation has is stored here, and whichever submission proves the higher existing UID is
// deemed correct, assuming it also matches the UID for the new reputation being inserted.
}
// Records for which hashes, for which addresses, for which entries have been accepted
// Otherwise, people could keep submitting the same entry.
mapping (bytes32 => mapping(address => mapping(uint256 => bool))) submittedEntries;
/// @notice A modifier that checks that the supplied `roundNumber` is the final round
/// @param roundNumber The `roundNumber` to check if it is the final round
modifier finalDisputeRoundCompleted(uint roundNumber) {
require (nSubmittedHashes - nInvalidatedHashes == 1);
require (disputeRounds[roundNumber].length == 1); //i.e. this is the final round
// Note that even if we are passed the penultimate round, which had a length of two, and had one eliminated,
// and therefore 'delete' called in `invalidateHash`, the array still has a length of '2' - it's just that one
// element is zeroed. If this functionality of 'delete' is ever changed, this will have to change too.
_;
}
/// @notice A modifier that checks if the challenge corresponding to the hash in the passed `round` and `id` is open
/// @param round The round number of the hash under consideration
/// @param idx The index in the round of the hash under consideration
modifier challengeOpen(uint256 round, uint256 idx) {
// TODO: More checks that this is an appropriate time to respondToChallenge
require(disputeRounds[round][idx].lowerBound == disputeRounds[round][idx].upperBound);
_;
}
/// @notice A modifier that checks if the proposed entry is eligible. The more CLNY a user stakes, the more
/// potential entries they have in a reputation mining cycle. This is effectively restricting the nonce range
/// that is allowable from a given user when searching for a submission that will pass `withinTarget`. A user
/// is allowed to use multiple entries in a single cycle, but each entry can only be used once per cycle, and
/// if there are multiple entries they must all be for the same proposed Reputation State Root Hash with the
/// same number of nodes.
/// @param newHash The hash being submitted
/// @param nNodes The number of nodes in the reputation tree that `newHash` is the root hash of
/// @param entryIndex The number of the entry the submitter hash asked us to consider.
modifier entryQualifies(bytes32 newHash, uint256 nNodes, uint256 entryIndex) {
// TODO: Require minimum stake, that is (much) more than the cost required to defend the valid submission.
// Here, the minimum stake is 10**15.
require(entryIndex <= IColonyNetwork(colonyNetworkAddress).getStakedBalance(msg.sender) / 10**15);
require(entryIndex > 0);
if (reputationHashSubmissions[msg.sender].proposedNewRootHash != 0x0) { // If this user has submitted before during this round...
require(newHash == reputationHashSubmissions[msg.sender].proposedNewRootHash); // ...require that they are submitting the same hash ...
require(nNodes == reputationHashSubmissions[msg.sender].nNodes); // ...require that they are submitting the same number of nodes for that hash ...
require (submittedEntries[newHash][msg.sender][entryIndex] == false); // ... but not this exact entry
}
_;
}
/// @notice A modifier that checks if the proposed entry is within the current allowable submission window
/// @dev A submission will only be accepted from a reputation miner if `keccak256(address, N, hash) < target`
/// At the beginning of the submission window, the target is set to 0 and slowly increases to 2^256 - 1 after an hour
modifier withinTarget(bytes32 newHash, uint256 entryIndex) {
require(reputationMiningWindowOpenTimestamp > 0);
// Check the ticket is a winning one.
// TODO Figure out how to uncomment the next line, but not break tests sporadically.
// require((now-reputationMiningWindowOpenTimestamp) <= 3600);
// x = floor(uint((2**256 - 1) / 3600)
if (now - reputationMiningWindowOpenTimestamp <= 3600) {
uint256 x = 32164469232587832062103051391302196625908329073789045566515995557753647122;
uint256 target = (now - reputationMiningWindowOpenTimestamp ) * x;
require(uint256(getEntryHash(msg.sender, entryIndex, newHash)) < target);
}
_;
}
function getEntryHash(address submitter, uint256 entryIndex, bytes32 newHash) public pure returns (bytes32) {
return keccak256(abi.encodePacked(submitter, entryIndex, newHash));
}
/// @notice Constructor for this contract.
constructor() public {
colonyNetworkAddress = msg.sender;
}
function resetWindow() public {
require(msg.sender == colonyNetworkAddress);
reputationMiningWindowOpenTimestamp = now;
}
function submitRootHash(bytes32 newHash, uint256 nNodes, uint256 entryIndex)
entryQualifies(newHash, nNodes, entryIndex)
withinTarget(newHash, entryIndex)
public
{
// Limit the total number of miners allowed to submit a specific hash to 12
require (submittedHashes[newHash][nNodes].length < 12);
// If this is a new hash, increment nSubmittedHashes as such.
if (submittedHashes[newHash][nNodes].length == 0) {
nSubmittedHashes += 1;
// And add it to the first disputeRound
// NB if no other hash is submitted, no dispute resolution will be required.
disputeRounds[0].push(Submission({
proposedNewRootHash: newHash,
jrh: 0x0,
nNodes: nNodes,
lastResponseTimestamp: 0,
challengeStepCompleted: 0,
lowerBound: 0,
upperBound: 0,
jrhNnodes: 0,
intermediateReputationHash: 0x0,
intermediateReputationNNodes: 0,
provedPreviousReputationUID: 0
}));
// If we've got a pair of submissions to face off, may as well start now.
if (nSubmittedHashes % 2 == 0) {
disputeRounds[0][nSubmittedHashes-1].lastResponseTimestamp = now;
disputeRounds[0][nSubmittedHashes-2].lastResponseTimestamp = now;
/* disputeRounds[0][nSubmittedHashes-1].upperBound = disputeRounds[0][nSubmittedHashes-1].jrhNnodes; */
/* disputeRounds[0][nSubmittedHashes-2].upperBound = disputeRounds[0][nSubmittedHashes-2].jrhNnodes; */
}
}
reputationHashSubmissions[msg.sender] = Submission({
proposedNewRootHash: newHash,
jrh: 0x0,
nNodes: nNodes,
lastResponseTimestamp: 0,
challengeStepCompleted: 0,
lowerBound: 0,
upperBound: 0,
jrhNnodes: 0,
intermediateReputationHash: 0x0,
intermediateReputationNNodes: 0,
provedPreviousReputationUID: 0
});
// And add the miner to the array list of submissions here
submittedHashes[newHash][nNodes].push(msg.sender);
// Note that they submitted it.
submittedEntries[newHash][msg.sender][entryIndex] = true;
}
function confirmNewHash(uint256 roundNumber) public
finalDisputeRoundCompleted(roundNumber)
{
// TODO: Require some amount of time to have passed (i.e. people have had a chance to submit other hashes)
Submission storage submission = disputeRounds[roundNumber][0];
IColonyNetwork(colonyNetworkAddress).setReputationRootHash(submission.proposedNewRootHash, submission.nNodes, submittedHashes[submission.proposedNewRootHash][submission.nNodes]);
selfdestruct(colonyNetworkAddress);
}
function invalidateHash(uint256 round, uint256 idx) public {
// What we do depends on our opponent, so work out which index it was at in disputeRounds[round]
uint256 opponentIdx = (idx % 2 == 1 ? idx-1 : idx + 1);
uint256 nInNextRound;
// We require either
// 1. That we actually had an opponent - can't invalidate the last hash.
// 2. This cycle had an odd number of submissions, which was larger than 1, and we're giving the last entry a bye to the next round.
if (disputeRounds[round].length % 2 == 1 && disputeRounds[round].length == idx) {
// This is option two above - note that because arrays are zero-indexed, if idx==length, then
// this is the slot after the last entry, and so our opponentIdx will be the last entry
// We just move the opponent on, and nothing else happens.
// Ensure that the previous round is complete, and this entry wouldn't possibly get an opponent later on.
require(nHashesCompletedChallengeRound[round-1] == disputeRounds[round-1].length);
// Prevent us invalidating the final hash
require(disputeRounds[round].length > 1);
// Move opponent on to next round
disputeRounds[round+1].push(disputeRounds[round][opponentIdx]);
delete disputeRounds[round][opponentIdx];
// Note the fact that this round has had another challenge complete
nHashesCompletedChallengeRound[round] += 1;
// Check if the hash we just moved to the next round is the second of a pairing that should now face off.
nInNextRound = disputeRounds[round+1].length;
if (nInNextRound % 2 == 0) {
startPairingInRound(round+1);
}
} else {
require(disputeRounds[round].length > opponentIdx);
require(disputeRounds[round][opponentIdx].proposedNewRootHash != "");
// Require that this is not better than its opponent.
require(disputeRounds[round][opponentIdx].challengeStepCompleted >= disputeRounds[round][idx].challengeStepCompleted);
require(disputeRounds[round][opponentIdx].provedPreviousReputationUID >= disputeRounds[round][idx].provedPreviousReputationUID);
// Require that it has failed a challenge (i.e. failed to respond in time)
require(now - disputeRounds[round][idx].lastResponseTimestamp >= 600); //'In time' is ten minutes here.
// Work out whether we are invalidating just the supplied idx or its opponent too.
bool eliminateOpponent = false;
if (disputeRounds[round][opponentIdx].challengeStepCompleted == disputeRounds[round][idx].challengeStepCompleted &&
disputeRounds[round][opponentIdx].provedPreviousReputationUID == disputeRounds[round][idx].provedPreviousReputationUID) {
eliminateOpponent = true;
}
if (!eliminateOpponent) {
// If here, then the opponent completed one more challenge round than the submission being invalidated or
// proved a later UID was in the tree, so we don't know if they're valid or not yet. Move them on to the next round.
disputeRounds[round+1].push(disputeRounds[round][opponentIdx]);
delete disputeRounds[round][opponentIdx];
// TODO Delete the hash(es) being invalidated?
nInvalidatedHashes += 1;
// Check if the hash we just moved to the next round is the second of a pairing that should now face off.
nInNextRound = disputeRounds[round+1].length;
if (nInNextRound % 2 == 0) {
startPairingInRound(round+1);
}
} else {
// Our opponent completed the same number of challenge rounds, and both have now timed out.
nInvalidatedHashes += 2;
// Punish the people who proposed our opponent
IColonyNetwork(colonyNetworkAddress).punishStakers(submittedHashes[disputeRounds[round][opponentIdx].proposedNewRootHash][disputeRounds[round][opponentIdx].nNodes]);
}
// Note that two hashes have completed this challenge round (either one accepted for now and one rejected, or two rejected)
nHashesCompletedChallengeRound[round] += 2;
// Punish the people who proposed the hash that was rejected
IColonyNetwork(colonyNetworkAddress).punishStakers(submittedHashes[disputeRounds[round][idx].proposedNewRootHash][disputeRounds[round][idx].nNodes]);
}
//TODO: Can we do some deleting to make calling this as cheap as possible for people?
}
function respondToBinarySearchForChallenge(uint256 round, uint256 idx, bytes jhIntermediateValue, uint branchMask, bytes32[] siblings) public {
// TODO: Check this challenge is active.
// This require is necessary, but not a sufficient check (need to check we have an opponent, at least).
require(disputeRounds[round][idx].lowerBound!=disputeRounds[round][idx].upperBound);
uint256 targetNode = add(disputeRounds[round][idx].lowerBound, sub(disputeRounds[round][idx].upperBound, disputeRounds[round][idx].lowerBound) / 2);
bytes32 jrh = disputeRounds[round][idx].jrh;
bytes memory targetNodeBytes = new bytes(32);
assembly {
mstore(add(targetNodeBytes, 0x20), targetNode)
}
bytes32 impliedRoot = getImpliedRoot(targetNodeBytes, jhIntermediateValue, branchMask, siblings);
require(impliedRoot==jrh, "colony-invalid-binary-search-response");
// If require hasn't thrown, proof is correct.
// Process the consequences
processBinaryChallengeSearchResponse(round, idx, jhIntermediateValue, targetNode);
}
uint constant U_ROUND = 0;
uint constant U_IDX = 1;
uint constant U_REPUTATION_BRANCH_MASK = 2;
uint constant U_AGREE_STATE_NNODES = 3;
uint constant U_AGREE_STATE_BRANCH_MASK = 4;
uint constant U_DISAGREE_STATE_NNODES = 5;
uint constant U_DISAGREE_STATE_BRANCH_MASK = 6;
uint constant U_PREVIOUS_NEW_REPUTATION_BRANCH_MASK = 7;
uint constant U_REQUIRE_REPUTATION_CHECK = 8;
function respondToChallenge(
uint256[9] u, //An array of 9 UINT Params, ordered as given above.
bytes _reputationKey,
bytes32[] reputationSiblings,
bytes agreeStateReputationValue,
bytes32[] agreeStateSiblings,
bytes disagreeStateReputationValue,
bytes32[] disagreeStateSiblings,
bytes previousNewReputationKey,
bytes previousNewReputationValue,
bytes32[] previousNewReputationSiblings
) public
challengeOpen(u[U_ROUND], u[U_IDX])
{
u[U_REQUIRE_REPUTATION_CHECK] = 0;
// TODO: More checks that this is an appropriate time to respondToChallenge (maybe in modifier);
/* bytes32 jrh = disputeRounds[round][idx].jrh; */
// The contract knows
// 1. the jrh for this submission
// 2. The first index where this submission and its opponent differ.
// Need to prove
// 1. The reputation that is updated that we disagree on's value, before the first index
// where we differ, and in the first index where we differ.
// 2. That no other changes are made to the reputation state. The proof for those
// two reputations in (1) is therefore required to be the same.
// 3. That our 'after' value is correct. This is done by doing the calculation on-chain, perhaps
// after looking up the corresponding entry in the reputation update log (the alternative is
// that it's a decay calculation - not yet implemented.)
// Check the supplied key is appropriate.
checkKey(u[U_ROUND], u[U_IDX], _reputationKey);
// Prove the reputation's starting value is in some state, and that state is in the appropriate index in our JRH
proveBeforeReputationValue(u, _reputationKey, reputationSiblings, agreeStateReputationValue, agreeStateSiblings);
// Prove the reputation's final value is in a particular state, and that state is in our JRH in the appropriate index (corresponding to the first disagreement between these miners)
// By using the same branchMask and siblings, we know that no other changes to the reputation state tree have been slipped in.
proveAfterReputationValue(u, _reputationKey, reputationSiblings, disagreeStateReputationValue, disagreeStateSiblings);
// Perform the reputation calculation ourselves.
performReputationCalculation(u, agreeStateReputationValue, disagreeStateReputationValue, previousNewReputationValue);
// If necessary, check the supplied previousNewRepuation is, in fact, in the same reputation state as the agreeState
if (u[U_REQUIRE_REPUTATION_CHECK]==1) {
checkPreviousReputationInState(
u,
_reputationKey,
reputationSiblings,
agreeStateReputationValue,
agreeStateSiblings,
previousNewReputationKey,
previousNewReputationValue,
previousNewReputationSiblings);
saveProvedReputation(u, previousNewReputationValue);
}
// If everthing checked out, note that we've responded to the challenge.
disputeRounds[u[U_ROUND]][u[U_IDX]].challengeStepCompleted += 1;
disputeRounds[u[U_ROUND]][u[U_IDX]].lastResponseTimestamp = now;
// Safety net?
/* if (disputeRounds[round][idx].challengeStepCompleted==disputeRounds[round][opponentIdx].challengeStepCompleted){
// Freeze the reputation mining system.
} */
}
function submitJustificationRootHash(
uint256 round,
uint256 index,
bytes32 jrh,
uint branchMask1,
bytes32[] siblings1,
uint branchMask2,
bytes32[] siblings2
) public
{
// Require we've not submitted already.
require(disputeRounds[round][index].jrh == 0x0);
// Check the proofs for the JRH
checkJRHProof1(jrh, branchMask1, siblings1);
checkJRHProof2(round, index, jrh, branchMask2, siblings2);
// Store their JRH
disputeRounds[round][index].jrh = jrh;
disputeRounds[round][index].lastResponseTimestamp = now;
disputeRounds[round][index].challengeStepCompleted += 1;
// Set bounds for first binary search if it's going to be needed
disputeRounds[round][index].upperBound = disputeRounds[round][index].jrhNnodes;
}
function appendReputationUpdateLog(address _user, int _amount, uint _skillId, address _colonyAddress, uint _nParents, uint _nChildren) public {
require(colonyNetworkAddress == msg.sender);
uint reputationUpdateLogLength = reputationUpdateLog.length;
uint nPreviousUpdates = 0;
if (reputationUpdateLogLength > 0) {
nPreviousUpdates = reputationUpdateLog[reputationUpdateLogLength-1].nPreviousUpdates + reputationUpdateLog[reputationUpdateLogLength-1].nUpdates;
}
uint nUpdates = (_nParents + 1) * 2;
if (_amount < 0) {
//TODO: Never true currently. _amount needs to be an int.
nUpdates += 2 * _nChildren;
}
reputationUpdateLog.push(ReputationLogEntry(
_user,
_amount,
_skillId,
_colonyAddress,
nUpdates,
nPreviousUpdates));
}
function getReputationUpdateLogLength() public view returns (uint) {
return reputationUpdateLog.length;
}
function getReputationUpdateLogEntry(uint256 _id) public view returns (address, int256, uint256, address, uint256, uint256) {
ReputationLogEntry storage x = reputationUpdateLog[_id];
return (x.user, x.amount, x.skillId, x.colony, x.nUpdates, x.nPreviousUpdates);
}
function rewardStakersWithReputation(address[] stakers, address commonColonyAddress, uint reward) public {
require(reputationUpdateLog.length==0);
require(msg.sender == colonyNetworkAddress);
for (uint256 i = 0; i < stakers.length; i++) {
// We *know* we're the first entries in this reputation update log, so we don't need all the bookkeeping in
// the AppendReputationUpdateLog function
reputationUpdateLog.push(ReputationLogEntry(
stakers[i],
int256(reward),
0, //TODO: Work out what skill this should be. This should be a special 'mining' skill.
commonColonyAddress, // They earn this reputation in the common colony.
4, // Updates the user's skill, and the colony's skill, both globally and for the special 'mining' skill
i*4 //We're zero indexed, so this is the number of updates that came before in the reputation log.
));
}
}
/////////////////////////
// Internal functions
/////////////////////////
function processBinaryChallengeSearchResponse(uint256 round, uint256 idx, bytes jhIntermediateValue, uint256 targetNode) internal {
disputeRounds[round][idx].lastResponseTimestamp = now;
disputeRounds[round][idx].challengeStepCompleted += 1;
// Save our intermediate hash
bytes32 intermediateReputationHash;
uint256 intermediateReputationNNodes;
assembly {
intermediateReputationHash := mload(add(jhIntermediateValue, 0x20))
intermediateReputationNNodes := mload(add(jhIntermediateValue, 0x40))
}
disputeRounds[round][idx].intermediateReputationHash = intermediateReputationHash;
disputeRounds[round][idx].intermediateReputationNNodes = intermediateReputationNNodes;
uint256 opponentIdx = (idx % 2 == 1 ? idx-1 : idx + 1);
if (disputeRounds[round][opponentIdx].challengeStepCompleted == disputeRounds[round][idx].challengeStepCompleted ) {
// Our opponent answered this challenge already.
// Compare our intermediateReputationHash to theirs to establish how to move the bounds.
processBinaryChallengeSearchStep(round, idx, targetNode);
}
}
function processBinaryChallengeSearchStep(uint256 round, uint256 idx, uint256 targetNode) internal {
uint256 opponentIdx = (idx % 2 == 1 ? idx-1 : idx + 1);
if (
disputeRounds[round][opponentIdx].intermediateReputationHash == disputeRounds[round][idx].intermediateReputationHash &&
disputeRounds[round][opponentIdx].intermediateReputationNNodes == disputeRounds[round][idx].intermediateReputationNNodes
)
{
disputeRounds[round][idx].lowerBound = targetNode + 1;
disputeRounds[round][opponentIdx].lowerBound = targetNode + 1;
} else {
// NB no '-1' to mirror the '+1' above in the other bound, because
// we're looking for the first index where these two submissions differ
// in their calculations - they disagreed for this index, so this might
// be the first index they disagree about
disputeRounds[round][idx].upperBound = targetNode;
disputeRounds[round][opponentIdx].upperBound = targetNode;
}
// We need to keep the intermediate hashes so that we can figure out what type of dispute we are resolving later
// If the number of nodes in the reputation state are different, then we are disagreeing on whether this log entry
// corresponds to an existing reputation entry or not.
// If the hashes are different, then it's a calculation error.
// Our opponent responded to this step of the challenge before we did, so we should
// reset their 'last response' time to now, as they aren't able to respond
// to the next challenge before they know what it is!
disputeRounds[round][opponentIdx].lastResponseTimestamp = now;
}
function checkKey( uint256 round, uint256 idx, bytes memory _reputationKey) internal {
// If the state transition we're checking is less than the number of nodes in the currently accepted state, it's a decay transition (TODO: not implemented)
// Otherwise, look up the corresponding entry in the reputation log.
uint256 updateNumber = disputeRounds[round][idx].lowerBound - 1;
bytes memory reputationKey = new bytes(20+32+20);
reputationKey = _reputationKey;
address colonyAddress;
address userAddress;
uint256 skillId;
assembly {
colonyAddress := mload(add(reputationKey,20)) // 20, not 32, because we're copying in to a slot that will be interpreted as an address.
// which will truncate the leftmost 12 bytes
skillId := mload(add(reputationKey, 52))
userAddress := mload(add(reputationKey,72)) // 72, not 84, for the same reason as above. Is this being too clever? I don't think there are
// any unintended side effects here, but I'm not quite confortable enough with EVM's stack to be sure.
// Not sure what the alternative would be anyway.
}
bool decayCalculation = false;
if (decayCalculation) {
} else {
require(reputationUpdateLog[updateNumber].user == userAddress);
require(reputationUpdateLog[updateNumber].colony == colonyAddress);
require(reputationUpdateLog[updateNumber].skillId == skillId);
}
}
function proveBeforeReputationValue(uint256[9] u, bytes _reputationKey, bytes32[] reputationSiblings, bytes agreeStateReputationValue, bytes32[] agreeStateSiblings) internal {
bytes32 jrh = disputeRounds[u[U_ROUND]][u[U_IDX]].jrh;
uint256 lastAgreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1; // We binary searched to the first disagreement, so the last agreement is the one before.
uint256 reputationValue;
assembly {
reputationValue := mload(add(agreeStateReputationValue, 32))
}
bytes32 reputationRootHash = getImpliedRoot(_reputationKey, agreeStateReputationValue, u[U_REPUTATION_BRANCH_MASK], reputationSiblings);
bytes memory jhLeafValue = new bytes(64);
bytes memory lastAgreeIdxBytes = new bytes(32);
assembly {
mstore(add(jhLeafValue, 0x20), reputationRootHash)
let x := mload(add(u, mul(32,3))) // 3 = U_AGREE_STATE_NNODES. Constants not supported by inline solidity
mstore(add(jhLeafValue, 0x40), x)
mstore(add(lastAgreeIdxBytes, 0x20), lastAgreeIdx)
}
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions
// agree on.
bytes32 impliedRoot = getImpliedRoot(lastAgreeIdxBytes, jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
if (reputationValue == 0 && impliedRoot != jrh) {
// This implies they are claiming that this is a new hash.
return;
}
require(impliedRoot == jrh);
// They've actually verified whatever they claimed. We increment their challengeStepCompleted by one to indicate this.
// In the event that our opponent lied about this reputation not existing yet in the tree, they will both complete
// a call to respondToChallenge, but we will have a higher challengeStepCompleted value, and so they will be the ones
// eliminated.
disputeRounds[u[U_ROUND]][u[U_IDX]].challengeStepCompleted += 1;
// I think this trick can be used exactly once, and only because this is the last function to be called in the challege,
// and I'm choosing to use it here. I *think* this is okay, because the only situation
// where we don't prove anything with merkle proofs in this whole dance is here.
}
function proveAfterReputationValue(uint256[9] u, bytes _reputationKey, bytes32[] reputationSiblings, bytes disagreeStateReputationValue, bytes32[] disagreeStateSiblings) internal {
bytes32 jrh = disputeRounds[u[U_ROUND]][u[U_IDX]].jrh;
uint256 firstDisagreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound;
bytes32 reputationRootHash = getImpliedRoot(_reputationKey, disagreeStateReputationValue, u[U_REPUTATION_BRANCH_MASK], reputationSiblings);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions
// agree on.
bytes memory jhLeafValue = new bytes(64);
bytes memory firstDisagreeIdxBytes = new bytes(32);
assembly {
mstore(add(jhLeafValue, 0x20), reputationRootHash)
let x := mload(add(u, mul(32,5))) // 5 = U_DISAGREE_STATE_NNODES. Constants not supported by inline solidity.
mstore(add(jhLeafValue, 0x40), x)
mstore(add(firstDisagreeIdxBytes, 0x20), firstDisagreeIdx)
}
bytes32 impliedRoot = getImpliedRoot(firstDisagreeIdxBytes, jhLeafValue, u[U_DISAGREE_STATE_BRANCH_MASK], disagreeStateSiblings);
require(jrh==impliedRoot, "colony-invalid-after-reputation-proof");
}
function performReputationCalculation(uint256[9] u, bytes agreeStateReputationValueBytes, bytes disagreeStateReputationValueBytes, bytes previousNewReputationValueBytes) internal {
// TODO: Possibility of decay calculation
uint reputationTransitionIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1;
int256 amount;
uint256 agreeStateReputationValue;
uint256 disagreeStateReputationValue;
uint256 agreeStateReputationUID;
uint256 disagreeStateReputationUID;
assembly {
agreeStateReputationValue := mload(add(agreeStateReputationValueBytes, 32))
disagreeStateReputationValue := mload(add(disagreeStateReputationValueBytes, 32))
agreeStateReputationUID := mload(add(agreeStateReputationValueBytes, 64))
disagreeStateReputationUID := mload(add(disagreeStateReputationValueBytes, 64))
}
if (agreeStateReputationUID != 0) {
// i.e. if this was an existing reputation, then require that the ID hasn't changed.
// TODO: Situation where it is not an existing reputation
require(agreeStateReputationUID==disagreeStateReputationUID);
} else {
uint256 previousNewReputationUID;
assembly {
previousNewReputationUID := mload(add(previousNewReputationValueBytes, 64))
}
require(previousNewReputationUID+1 == disagreeStateReputationUID);
// Flag that we need to check that the reputation they supplied is in the 'agree' state.
// This feels like it might be being a bit clever, using this array to pass a 'return' value out of
// this function, without adding a new variable to the stack in the parent function...
u[U_REQUIRE_REPUTATION_CHECK] = 1;
}
// We don't care about underflows for the purposes of comparison, but for the calculation we deem 'correct'.
// i.e. a reputation can't be negative.
if (reputationUpdateLog[reputationTransitionIdx].amount < 0 && uint(reputationUpdateLog[reputationTransitionIdx].amount * -1) > agreeStateReputationValue ) {
require(disagreeStateReputationValue == 0);
} else if (uint(reputationUpdateLog[reputationTransitionIdx].amount) + agreeStateReputationValue < agreeStateReputationValue) {
// We also don't allow reputation to overflow
require(disagreeStateReputationValue == 2**256 - 1);
} else {
// TODO: Is this safe? I think so, because even if there's over/underflows, they should
// still be the same number.
require(int(agreeStateReputationValue)+reputationUpdateLog[reputationTransitionIdx].amount == int(disagreeStateReputationValue));
}
}
function checkPreviousReputationInState(
uint256[9] u,
bytes _reputationKey,
bytes32[] reputationSiblings,
bytes agreeStateReputationValue,
bytes32[] agreeStateSiblings,
bytes previousNewReputationKey,
bytes previousNewReputationValue,
bytes32[] previousNewReputationSiblings)
internal
{
uint256 lastAgreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1; // We binary searched to the first disagreement, so the last agreement is the one before
bytes32 reputationRootHash = getImpliedRoot(previousNewReputationKey, previousNewReputationValue, u[U_PREVIOUS_NEW_REPUTATION_BRANCH_MASK], previousNewReputationSiblings);
bytes memory jhLeafValue = new bytes(64);
bytes memory lastAgreeIdxBytes = new bytes(32);
assembly {
mstore(add(jhLeafValue, 0x20), reputationRootHash)
let x := mload(add(u, mul(32,3))) // 3 = U_AGREE_STATE_NNODES. Constants not supported by inline assembly
mstore(add(jhLeafValue, 0x40), x)
mstore(add(lastAgreeIdxBytes, 0x20), lastAgreeIdx)
}
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on
bytes32 impliedRoot = getImpliedRoot(lastAgreeIdxBytes, jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
require(impliedRoot == disputeRounds[u[U_ROUND]][u[U_IDX]].jrh);
}
function saveProvedReputation(uint256[9] u, bytes previousNewReputationValue) internal {
uint256 previousReputationUID;
assembly {
previousReputationUID := mload(add(previousNewReputationValue,0x40))
}
// Save the index for tiebreak scenarios later.
disputeRounds[u[U_ROUND]][u[U_IDX]].provedPreviousReputationUID = previousReputationUID;
}
function checkJRHProof1(bytes32 jrh, uint branchMask1, bytes32[] siblings1) internal {
// Proof 1 needs to prove that they started with the current reputation root hash
bytes32 reputationRootHash = IColonyNetwork(colonyNetworkAddress).getReputationRootHash();
uint256 reputationRootHashNNodes = IColonyNetwork(colonyNetworkAddress).getReputationRootHashNNodes();
bytes memory jhLeafValue = new bytes(64);
bytes memory zero = new bytes(32);
assembly {
mstore(add(jhLeafValue, 0x20), reputationRootHash)
mstore(add(jhLeafValue, 0x40), reputationRootHashNNodes)
}
bytes32 impliedRoot = getImpliedRoot(zero, jhLeafValue, branchMask1, siblings1);
require(jrh==impliedRoot, "colony-invalid-jrh-proof-1");
}
function checkJRHProof2(uint round, uint index, bytes32 jrh, uint branchMask2, bytes32[] siblings2) internal {
// Proof 2 needs to prove that they finished with the reputation root hash they submitted, and the
// key is the number of updates in the reputation update log (implemented)
// plus the number of nodes in the last accepted update, each of which will have decayed once (not implemented)
// TODO: Account for decay calculations
uint256 nUpdates = reputationUpdateLog.length;
bytes memory nUpdatesBytes = new bytes(32);
disputeRounds[round][index].jrhNnodes = nUpdates + 1;
bytes32 submittedHash = disputeRounds[round][index].proposedNewRootHash;
uint256 submittedHashNNodes = disputeRounds[round][index].nNodes;
bytes memory jhLeafValue = new bytes(64);
assembly {
mstore(add(jhLeafValue, 0x20), submittedHash)
mstore(add(jhLeafValue, 0x40), submittedHashNNodes)
mstore(add(nUpdatesBytes, 0x20), nUpdates)
}
bytes32 impliedRoot = getImpliedRoot(nUpdatesBytes, jhLeafValue, branchMask2, siblings2);
require(jrh==impliedRoot, "colony-invalid-jrh-proof-2");
}
function startMemberOfPair(uint256 roundNumber, uint256 index) internal {
disputeRounds[roundNumber][index].lastResponseTimestamp = now;
disputeRounds[roundNumber][index].upperBound = disputeRounds[roundNumber][index].jrhNnodes;
disputeRounds[roundNumber][index].lowerBound = 0;
disputeRounds[roundNumber][index].provedPreviousReputationUID = 0;
if (disputeRounds[roundNumber][index].jrh != 0x0) {
// If this submission has a JRH, we give ourselves credit for it in the next round - it's possible
// that a submission got a bye without submitting a JRH, which will not have this starting '1'.
disputeRounds[roundNumber][index].challengeStepCompleted = 1;
} else {
disputeRounds[roundNumber][index].challengeStepCompleted = 0;
}
}
function startPairingInRound(uint256 roundNumber) internal {
uint256 nInRound = disputeRounds[roundNumber].length;
startMemberOfPair(roundNumber, nInRound-1);
startMemberOfPair(roundNumber, nInRound-2);
}
}
| Require that this is not better than its opponent. | require(disputeRounds[round][opponentIdx].challengeStepCompleted >= disputeRounds[round][idx].challengeStepCompleted);
| 12,759,860 | [
1,
8115,
716,
333,
353,
486,
7844,
2353,
2097,
1061,
1029,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1377,
2583,
12,
2251,
2507,
54,
9284,
63,
2260,
6362,
556,
1029,
4223,
8009,
25092,
4160,
9556,
1545,
1015,
2507,
54,
9284,
63,
2260,
6362,
3465,
8009,
25092,
4160,
9556,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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";
/**
* @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 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 "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "./interfaces/bloq/IAddressList.sol";
import "./interfaces/bloq/IAddressListFactory.sol";
import "./interfaces/compound/ICompound.sol";
import "./interfaces/IVUSD.sol";
/// @title Minter contract which will mint VUSD 1:1, less minting fee, with DAI, USDC or USDT.
contract Minter is Context, ReentrancyGuard {
using SafeERC20 for IERC20;
string public constant NAME = "VUSD-Minter";
string public constant VERSION = "1.2.1";
IAddressList public immutable whitelistedTokens;
IVUSD public immutable vusd;
uint256 public mintingFee; // Default no fee
uint256 public constant MAX_MINTING_FEE = 10_000; // 10_000 = 100%
uint256 public constant MINT_LIMIT = 50_000_000 * 10**18; // 50M VUSD
mapping(address => address) public cTokens;
address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
event UpdatedMintingFee(uint256 previousMintingFee, uint256 newMintingFee);
constructor(address _vusd) {
require(_vusd != address(0), "vusd-address-is-zero");
vusd = IVUSD(_vusd);
IAddressListFactory _factory = IAddressListFactory(0xded8217De022706A191eE7Ee0Dc9df1185Fb5dA3);
IAddressList _whitelistedTokens = IAddressList(_factory.createList());
// Add token into the list, add cToken into the mapping and approve cToken to spend token
_addToken(_whitelistedTokens, DAI, address(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643));
_addToken(_whitelistedTokens, USDC, address(0x39AA39c021dfbaE8faC545936693aC917d5E7563));
_addToken(_whitelistedTokens, USDT, address(0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9));
whitelistedTokens = _whitelistedTokens;
}
modifier onlyGovernor() {
require(_msgSender() == governor(), "caller-is-not-the-governor");
_;
}
////////////////////////////// Only Governor //////////////////////////////
/**
* @notice Add token as whitelisted token for VUSD system
* @dev Add token address in whitelistedTokens list and add cToken in mapping
* @param _token address which we want to add in token list.
* @param _cToken CToken address correspond to _token
*/
function addWhitelistedToken(address _token, address _cToken) external onlyGovernor {
_addToken(whitelistedTokens, _token, _cToken);
}
/**
* @notice Remove token from whitelisted tokens
* @param _token address which we want to remove from token list.
*/
function removeWhitelistedToken(address _token) external onlyGovernor {
require(whitelistedTokens.remove(_token), "remove-from-list-failed");
IERC20(_token).safeApprove(cTokens[_token], 0);
delete cTokens[_token];
}
/// @notice Update minting fee
function updateMintingFee(uint256 _newMintingFee) external onlyGovernor {
require(_newMintingFee <= MAX_MINTING_FEE, "minting-fee-limit-reached");
require(mintingFee != _newMintingFee, "same-minting-fee");
emit UpdatedMintingFee(mintingFee, _newMintingFee);
mintingFee = _newMintingFee;
}
///////////////////////////////////////////////////////////////////////////
/**
* @notice Mint VUSD
* @param _token Address of token being deposited
* @param _amount Amount of _token
*/
function mint(address _token, uint256 _amount) external nonReentrant {
_mint(_token, _amount, _msgSender());
}
/**
* @notice Mint VUSD
* @param _token Address of token being deposited
* @param _amount Amount of _token
* @param _receiver Address of VUSD receiver
*/
function mint(
address _token,
uint256 _amount,
address _receiver
) external nonReentrant {
_mint(_token, _amount, _receiver);
}
/**
* @notice Calculate mintage for supported tokens.
* @param _token Address of token which will be deposited for this mintage
* @param _amount Amount of _token
*/
function calculateMintage(address _token, uint256 _amount) external view returns (uint256 _mintReturn) {
if (whitelistedTokens.contains(_token)) {
(uint256 _mintage, ) = _calculateMintage(_token, _amount);
return _mintage;
}
// Return 0 for unsupported tokens.
return 0;
}
/// @notice Check available mintage based on mint limit
function availableMintage() public view returns (uint256 _mintage) {
return MINT_LIMIT - vusd.totalSupply();
}
/// @dev Treasury is defined in VUSD token contract only
function treasury() public view returns (address) {
return vusd.treasury();
}
/// @dev Governor is defined in VUSD token contract only
function governor() public view returns (address) {
return vusd.governor();
}
/**
* @dev Add _token into the list, add _cToken in mapping and
* approve cToken to spend token
*/
function _addToken(
IAddressList _list,
address _token,
address _cToken
) internal {
require(_list.add(_token), "add-in-list-failed");
cTokens[_token] = _cToken;
IERC20(_token).safeApprove(_cToken, type(uint256).max);
}
/**
* @notice Mint VUSD
* @param _token Address of token being deposited
* @param _amount Amount of _token
* @param _receiver Address of VUSD receiver
*/
function _mint(
address _token,
uint256 _amount,
address _receiver
) internal {
require(whitelistedTokens.contains(_token), "token-is-not-supported");
(uint256 _mintage, uint256 _actualAmount) = _calculateMintage(_token, _amount);
require(_mintage != 0, "mint-limit-reached");
IERC20(_token).safeTransferFrom(_msgSender(), address(this), _actualAmount);
address _cToken = cTokens[_token];
require(CToken(_cToken).mint(_actualAmount) == 0, "cToken-mint-failed");
IERC20(_cToken).safeTransfer(treasury(), IERC20(_cToken).balanceOf(address(this)));
vusd.mint(_receiver, _mintage);
}
/**
* @notice Calculate mintage based on mintingFee, if any.
* Also covert _token defined decimal amount to 18 decimal amount
* @return _mintage VUSD mintage based on given input
* @return _actualAmount Actual token amount used for _mintage
*/
function _calculateMintage(address _token, uint256 _amount)
internal
view
returns (uint256 _mintage, uint256 _actualAmount)
{
uint256 _decimals = IERC20Metadata(_token).decimals();
uint256 _availableAmount = availableMintage() / 10**(18 - _decimals);
_actualAmount = (_amount > _availableAmount) ? _availableAmount : _amount;
_mintage = (mintingFee != 0) ? _actualAmount - ((_actualAmount * mintingFee) / MAX_MINTING_FEE) : _actualAmount;
// Convert final amount to 18 decimals
_mintage = _mintage * 10**(18 - _decimals);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IVUSD is IERC20, IERC20Permit {
function burnFrom(address _user, uint256 _amount) external;
function mint(address _to, uint256 _amount) external;
function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool);
function updateMinter(address _newMinter) external;
function updateTreasury(address _newTreasury) external;
function governor() external view returns (address _governor);
function minter() external view returns (address _minter);
function treasury() external view returns (address _treasury);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IAddressList {
function add(address a) external returns (bool);
function remove(address a) external returns (bool);
function at(uint256 index) external view returns (address, uint256);
function get(address a) external view returns (uint256);
function contains(address a) external view returns (bool);
function length() external view returns (uint256);
function grantRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IAddressListFactory {
function ours(address a) external view returns (bool);
function listCount() external view returns (uint256);
function listAt(uint256 idx) external view returns (address);
function createList() external returns (address listaddr);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface CToken is IERC20 {
function accrueInterest() external returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function mint() external payable; // For ETH
function mint(uint256 mintAmount) external returns (uint256); // For ERC20
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
}
interface Comptroller {
function claimComp(address holder, address[] memory) external;
function compAccrued(address holder) external view returns (uint256);
} | * @notice Calculate mintage based on mintingFee, if any. Also covert _token defined decimal amount to 18 decimal amount @return _mintage VUSD mintage based on given input @return _actualAmount Actual token amount used for _mintage/ Convert final amount to 18 decimals | function _calculateMintage(address _token, uint256 _amount)
internal
view
returns (uint256 _mintage, uint256 _actualAmount)
{
uint256 _decimals = IERC20Metadata(_token).decimals();
uint256 _availableAmount = availableMintage() / 10**(18 - _decimals);
_actualAmount = (_amount > _availableAmount) ? _availableAmount : _amount;
_mintage = (mintingFee != 0) ? _actualAmount - ((_actualAmount * mintingFee) / MAX_MINTING_FEE) : _actualAmount;
_mintage = _mintage * 10**(18 - _decimals);
}
| 499,074 | [
1,
8695,
312,
474,
410,
2511,
603,
312,
474,
310,
14667,
16,
309,
1281,
18,
8080,
1825,
1097,
389,
2316,
2553,
6970,
3844,
358,
6549,
6970,
3844,
327,
389,
81,
474,
410,
776,
3378,
40,
312,
474,
410,
2511,
603,
864,
810,
327,
389,
18672,
6275,
23788,
1147,
3844,
1399,
364,
389,
81,
474,
410,
19,
4037,
727,
3844,
358,
6549,
15105,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
11162,
49,
474,
410,
12,
2867,
389,
2316,
16,
2254,
5034,
389,
8949,
13,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
389,
81,
474,
410,
16,
2254,
5034,
389,
18672,
6275,
13,
203,
565,
288,
203,
3639,
2254,
5034,
389,
31734,
273,
467,
654,
39,
3462,
2277,
24899,
2316,
2934,
31734,
5621,
203,
3639,
2254,
5034,
389,
5699,
6275,
273,
2319,
49,
474,
410,
1435,
342,
1728,
636,
12,
2643,
300,
389,
31734,
1769,
203,
3639,
389,
18672,
6275,
273,
261,
67,
8949,
405,
389,
5699,
6275,
13,
692,
389,
5699,
6275,
294,
389,
8949,
31,
203,
3639,
389,
81,
474,
410,
273,
261,
81,
474,
310,
14667,
480,
374,
13,
692,
389,
18672,
6275,
300,
14015,
67,
18672,
6275,
380,
312,
474,
310,
14667,
13,
342,
4552,
67,
49,
3217,
1360,
67,
8090,
41,
13,
294,
389,
18672,
6275,
31,
203,
3639,
389,
81,
474,
410,
273,
389,
81,
474,
410,
380,
1728,
636,
12,
2643,
300,
389,
31734,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x386f593747e5B510c72511b439A90213C734bE17/sources/WinnerzNFT.sol | bytes4(keccak256(bytes('transfer(address,uint256)'))); | function safeTransfer(address token, address to, uint value, string memory err) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), err);
}
| 4,089,872 | [
1,
3890,
24,
12,
79,
24410,
581,
5034,
12,
3890,
2668,
13866,
12,
2867,
16,
11890,
5034,
2506,
3719,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4183,
5912,
12,
2867,
1147,
16,
1758,
358,
16,
2254,
460,
16,
533,
3778,
393,
13,
2713,
288,
203,
3639,
261,
6430,
2216,
16,
1731,
3778,
501,
13,
273,
1147,
18,
1991,
12,
21457,
18,
3015,
1190,
4320,
12,
20,
6995,
9349,
6162,
7358,
70,
16,
358,
16,
460,
10019,
203,
3639,
2583,
12,
4768,
597,
261,
892,
18,
2469,
422,
374,
747,
24126,
18,
3922,
12,
892,
16,
261,
6430,
3719,
3631,
393,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xd2B8805735ed574B3db38c1663a64e833B8CFeA7/sources/contracts/traits/implementers/UTAutographStorage.sol | Read the generic part of the trait for multiple tokens (the uint8 status value) | function getUint8Values(uint16[] memory _tokenIds) public view returns (uint8[] memory) {
uint8[] memory retval = new uint8[](_tokenIds.length);
for(uint16 i = 0; i < _tokenIds.length; i++) {
retval[i] = data[_tokenIds[i]].state;
}
return retval;
}
| 9,660,845 | [
1,
1994,
326,
5210,
1087,
434,
326,
13517,
364,
3229,
2430,
261,
5787,
2254,
28,
1267,
460,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
5487,
28,
1972,
12,
11890,
2313,
8526,
3778,
389,
2316,
2673,
13,
1071,
1476,
1135,
261,
11890,
28,
8526,
3778,
13,
288,
203,
3639,
2254,
28,
8526,
3778,
5221,
273,
394,
2254,
28,
8526,
24899,
2316,
2673,
18,
2469,
1769,
203,
3639,
364,
12,
11890,
2313,
277,
273,
374,
31,
277,
411,
389,
2316,
2673,
18,
2469,
31,
277,
27245,
288,
203,
5411,
5221,
63,
77,
65,
273,
501,
63,
67,
2316,
2673,
63,
77,
65,
8009,
2019,
31,
203,
3639,
289,
203,
3639,
327,
5221,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
interface IERC677Receiver {
function onTokenTransfer(address _sender, uint _value, bytes calldata _data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
interface ISideToken {
function mint(address account, uint256 amount, bytes calldata userData, bytes calldata operatorData) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
interface ISideTokenFactory {
function createSideToken(string calldata name, string calldata symbol, uint256 granularity) external returns(address);
event SideTokenCreated(address indexed sideToken, string symbol, uint256 granularity);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
// https://github.com/0xProject/0x-monorepo/blob/development/contracts/utils/contracts/src/LibEIP712.sol
library LibEIP712 {
// Hash of the EIP712 Domain Separator Schema
// keccak256(abi.encodePacked(
// "EIP712Domain(",
// "string name,",
// "string version,",
// "uint256 chainId,",
// "address verifyingContract",
// ")"
// ))
bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev Calculates a EIP712 domain separator.
/// @param name The EIP712 domain name.
/// @param version The EIP712 domain version.
/// @param verifyingContract The EIP712 verifying contract.
/// @return result EIP712 domain separator.
function hashEIP712Domain(
string memory name,
string memory version,
uint256 chainId,
address verifyingContract
)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH;
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
// keccak256(bytes(name)),
// keccak256(bytes(version)),
// chainId,
// uint256(verifyingContract)
// ))
// solium-disable-next-line security/no-inline-assembly
assembly {
// Calculate hashes of dynamic data
let nameHash := keccak256(add(name, 32), mload(name))
let versionHash := keccak256(add(version, 32), mload(version))
// Load free memory pointer
let memPtr := mload(64)
// Store params in memory
mstore(memPtr, schemaHash)
mstore(add(memPtr, 32), nameHash)
mstore(add(memPtr, 64), versionHash)
mstore(add(memPtr, 96), chainId)
mstore(add(memPtr, 128), verifyingContract)
// Compute hash
result := keccak256(memPtr, 160)
}
return result;
}
/// @dev Calculates EIP712 encoding for a hash struct with a given domain hash.
/// @param eip712DomainHash Hash of the domain domain separator data, computed
/// with getDomainHash().
/// @param hashStruct The EIP712 hash struct.
/// @return result EIP712 hash applied to the given EIP712 Domain.
function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct)
internal
pure
returns (bytes32 result)
{
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// EIP191_HEADER,
// EIP712_DOMAIN_HASH,
// hashStruct
// ));
// solium-disable-next-line security/no-inline-assembly
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./zeppelin/token/ERC777/ERC777.sol";
import "./IERC677Receiver.sol";
import "./ISideToken.sol";
import "./LibEIP712.sol";
contract SideToken is ISideToken, ERC777 {
using Address for address;
using SafeMath for uint256;
address public minter;
uint256 private _granularity;
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2612.md
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
// ERC677 Transfer Event
event Transfer(address,address,uint256,bytes);
constructor(string memory _tokenName, string memory _tokenSymbol, address _minterAddr, uint256 _newGranularity)
ERC777(_tokenName, _tokenSymbol, new address[](0)) {
require(_minterAddr != address(0), "SideToken: Empty Minter");
require(_newGranularity >= 1, "SideToken: Granularity < 1");
minter = _minterAddr;
_granularity = _newGranularity;
uint chainId;
// solium-disable-next-line security/no-inline-assembly
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = LibEIP712.hashEIP712Domain(
name(),
"1",
chainId,
address(this)
);
}
modifier onlyMinter() {
require(_msgSender() == minter, "SideToken: Caller is not the minter");
_;
}
function mint(
address account,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
)
external onlyMinter override
{
_mint(_msgSender(), account, amount, userData, operatorData);
}
/**
* @dev ERC677 transfer token with additional data if the recipient is a contact.
* @param recipient The address to transfer to.
* @param amount The amount to be transferred.
* @param data The extra data to be passed to the receiving contract.
*/
function transferAndCall(address recipient, uint amount, bytes calldata data)
external returns (bool success)
{
address from = _msgSender();
_send(from, from, recipient, amount, data, "", false);
emit Transfer(from, recipient, amount, data);
IERC677Receiver(recipient).onTokenTransfer(from, amount, data);
return true;
}
function granularity() public view override returns (uint256) {
return _granularity;
}
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2612.md
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, "SideToken: EXPIRED");
bytes32 digest = LibEIP712.hashEIP712Message(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "SideToken: INVALID_SIGNATURE");
_approve(owner, spender, value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./zeppelin/ownership/Secondary.sol";
import "./ISideTokenFactory.sol";
import "./SideToken.sol";
contract SideTokenFactory is ISideTokenFactory, Secondary {
function createSideToken(string calldata name, string calldata symbol, uint256 granularity)
external onlyPrimary override returns(address) {
address sideToken = address(new SideToken(name, symbol, primary(), granularity));
emit SideTokenCreated(sideToken, symbol, granularity);
return sideToken;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/*
* @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 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../GSN/Context.sol";
/**
* @dev A Secondary contract can only be used by its primary account (the one that created it).
*/
abstract contract Secondary is Context {
address private _primary;
/**
* @dev Emitted when the primary contract changes.
*/
event PrimaryTransferred(
address recipient
);
/**
* @dev Sets the primary account to the one that is creating the Secondary contract.
*/
constructor () {
_primary = _msgSender();
emit PrimaryTransferred(_primary);
}
/**
* @dev Reverts if called from any account other than the primary.
*/
modifier onlyPrimary() {
require(_msgSender() == _primary, "Secondary: caller is not the primary account");
_;
}
/**
* @return the address of the primary.
*/
function primary() public view returns (address) {
return _primary;
}
/**
* @dev Transfers contract to a new primary.
* @param recipient The address of new primary.
*/
function transferPrimary(address recipient) public onlyPrimary {
require(recipient != address(0), "Secondary: new primary is the zero address");
_primary = recipient;
emit PrimaryTransferred(_primary);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../GSN/Context.sol";
import "./IERC777.sol";
import "./IERC777Recipient.sol";
import "./IERC777Sender.sol";
import "../../token/ERC20/IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../introspection/IERC1820Registry.sol";
/**
* @dev Implementation of the {IERC777} 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}.
*
* 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.
*/
contract ERC777 is Context, IERC777, IERC20 {
using SafeMath for uint256;
using Address for address;
IERC1820Registry constant private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
// 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 private TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
// ERC20-allowances
mapping (address => mapping (address => uint256)) private _allowances;
/**
* @dev `defaultOperators` may be an empty array.
*/
constructor(
string memory aName,
string memory aSymbol,
address[] memory theDefaultOperators
) {
_name = aName;
_symbol = aSymbol;
_defaultOperatorsArray = theDefaultOperators;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
// register interfaces
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
/**
* @dev See {IERC777-name}.
*/
function name() public view override(IERC777) returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view override(IERC777) 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 pure override returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view virtual override(IERC777) returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view override(IERC20, IERC777) returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function send(address recipient, uint256 amount, bytes calldata data) external override(IERC777) {
_send(_msgSender(), _msgSender(), recipient, amount, data, "", true);
}
/**
* @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 override(IERC20) returns (bool) {
require(recipient != address(0), "ERC777: transfer to zero address");
address from = _msgSender();
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev See {IERC777-burn}.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes calldata data) external override(IERC777) {
_burn(_msgSender(), _msgSender(), amount, data, "");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(
address operator,
address tokenHolder
) public view override(IERC777) returns (bool) {
return operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) external override(IERC777) {
require(_msgSender() != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[_msgSender()][operator];
} else {
_operators[_msgSender()][operator] = true;
}
emit AuthorizedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) external override(IERC777) {
require(operator != _msgSender(), "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[_msgSender()][operator] = true;
} else {
delete _operators[_msgSender()][operator];
}
emit RevokedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view override(IERC777) 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 override(IERC777)
{
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator");
_send(_msgSender(), sender, recipient, amount, data, operatorData, true);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {Transfer} events.
*/
function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData)
external override(IERC777) {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator");
_burn(_msgSender(), 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 override(IERC20) 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 override(IERC20) returns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
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 override(IERC20) returns (bool) {
require(recipient != address(0), "ERC777: transfer to zero address");
require(holder != address(0), "ERC777: transfer from zero address");
address spender = _msgSender();
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance"));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(
address operator,
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal
{
require(account != address(0), "ERC777: mint to zero address");
// Update state variables
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, true);
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)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _send(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
internal
{
require(from != address(0), "ERC777: send from zero address");
require(to != address(0), "ERC777: send to zero address");
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
/**
* @dev Burn tokens
* @param operator address operator requesting the operation
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _burn(
address operator,
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
internal
{
require(from != address(0), "ERC777: burn from zero address");
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
// Update state variables
_balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal
{
_balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance");
_balances[to] = _balances[to].add(amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
function _approve(address holder, address spender, uint256 value) internal {
// TODO: restore this require statement if this function becomes internal, or is called at a new callsite. It is
// currently unnecessary.
//require(holder != address(0), "ERC777: approve from the zero address");
require(spender != address(0), "ERC777: approve to zero address");
_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
{
address implementer = _erc1820.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 if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
private
{
address implementer = _erc1820.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(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* [ERC1820 registry standard](https://eips.ethereum.org/EIPS/eip-1820) 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 `tokensReceived`
* 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 `tokensReceived`
* 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
);
function decimals() external returns (uint8);
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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @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
* [ERC1820 global registry](https://eips.ethereum.org/EIPS/eip-1820).
*
* 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,
uint amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @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
* [ERC1820 global registry](https://eips.ethereum.org/EIPS/eip-1820).
*
* 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,
uint amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @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 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: 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);
}
}
}
}
| * @dev See {IERC777-operatorBurn}. Emits {Burned} and {Transfer} events./ | function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData)
external override(IERC777) {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator");
_burn(_msgSender(), account, amount, data, operatorData);
}
| 1,423,174 | [
1,
9704,
288,
45,
654,
39,
14509,
17,
9497,
38,
321,
5496,
7377,
1282,
288,
38,
321,
329,
97,
471,
288,
5912,
97,
2641,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3726,
38,
321,
12,
2867,
2236,
16,
2254,
5034,
3844,
16,
1731,
745,
892,
501,
16,
1731,
745,
892,
3726,
751,
13,
203,
565,
3903,
3849,
12,
45,
654,
39,
14509,
13,
288,
203,
3639,
2583,
12,
291,
5592,
1290,
24899,
3576,
12021,
9334,
2236,
3631,
315,
654,
39,
14509,
30,
4894,
353,
486,
392,
3726,
8863,
203,
3639,
389,
70,
321,
24899,
3576,
12021,
9334,
2236,
16,
3844,
16,
501,
16,
3726,
751,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/56/0xF7Cb81E39bE4778B8f950F949edB4f5461B6036F/sources/MasterDrunk.sol | Pancake has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all. | function updateEmissionRate(uint256 _drunkPerBlock) public onlyOwner {
massUpdatePools();
drunkPerBlock = _drunkPerBlock;
}
| 11,141,573 | [
1,
4069,
23780,
711,
358,
527,
5949,
9609,
16000,
316,
1019,
358,
10182,
326,
801,
19710,
16,
2674,
732,
1221,
518,
4143,
471,
17270,
358,
777,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
1514,
19710,
4727,
12,
11890,
5034,
389,
3069,
1683,
2173,
1768,
13,
1071,
1338,
5541,
288,
203,
3639,
8039,
1891,
16639,
5621,
203,
3639,
5081,
1683,
2173,
1768,
273,
389,
3069,
1683,
2173,
1768,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
//
interface IERC20 {
function TOTALSUPPLY709() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF1000(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER912(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE643(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE378(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM696(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER249(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL928(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
//
abstract contract Context {
function _MSGSENDER905() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA980() 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;
}
}
//
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED618(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER905();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED618(address(0), msgSender);
}
function OWNER941() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER378() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER905(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP149() public virtual ONLYOWNER378 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED618(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP687(address newOwner) public virtual ONLYOWNER378 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED618(_owner, newOwner);
_owner = newOwner;
}
}
//
library SafeMath {
function ADD236(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB786(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB786(a, b, "SafeMath: subtraction overflow");
}
function SUB786(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 MUL747(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 DIV140(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV140(a, b, "SafeMath: division by zero");
}
function DIV140(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD599(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD599(a, b, "SafeMath: modulo by zero");
}
function MOD599(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
//
library Address {
function ISCONTRACT863(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// 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;
}
function SENDVALUE275(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL887(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL887(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL887(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE192(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE672(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE672(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE672(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE192(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE192(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT863(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
//
contract 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_entered586 = 1; //inject NONSTANDARD NAMING
uint256 private constant _entered769 = 2; //inject NONSTANDARD NAMING
uint256 private _status;
constructor () internal {
_status = _not_entered586;
}
modifier NONREENTRANT44() { //inject NONSTANDARD NAMING
// On the first call to nonReentrant, _notEntered will be true
require(_status != _entered769, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _entered769;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _not_entered586;
}
}
//
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER115(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.TRANSFER912.selector, to, value));
}
function SAFETRANSFERFROM287(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.TRANSFERFROM696.selector, from, to, value));
}
function SAFEAPPROVE190(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.ALLOWANCE643(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.APPROVE378.selector, spender, value));
}
function SAFEINCREASEALLOWANCE374(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE643(address(this), spender).ADD236(value);
_CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.APPROVE378.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE80(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE643(address(this), spender).SUB786(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.APPROVE378.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN516(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. 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).FUNCTIONCALL887(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
//
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME654() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL381() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS442() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY709() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF1000(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER912(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER205(_MSGSENDER905(), recipient, amount);
return true;
}
function ALLOWANCE643(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE378(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE516(_MSGSENDER905(), spender, amount);
return true;
}
function TRANSFERFROM696(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER205(sender, recipient, amount);
_APPROVE516(sender, _MSGSENDER905(), _allowances[sender][_MSGSENDER905()].SUB786(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE9(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE516(_MSGSENDER905(), spender, _allowances[_MSGSENDER905()][spender].ADD236(addedValue));
return true;
}
function DECREASEALLOWANCE999(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE516(_MSGSENDER905(), spender, _allowances[_MSGSENDER905()][spender].SUB786(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER205(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER183(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB786(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD236(amount);
emit TRANSFER249(sender, recipient, amount);
}
function _MINT985(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER183(address(0), account, amount);
_totalSupply = _totalSupply.ADD236(amount);
_balances[account] = _balances[account].ADD236(amount);
emit TRANSFER249(address(0), account, amount);
}
function _BURN126(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER183(account, address(0), amount);
_balances[account] = _balances[account].SUB786(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB786(amount);
emit TRANSFER249(account, address(0), amount);
}
function _APPROVE516(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL928(owner, spender, amount);
}
function _SETUPDECIMALS502(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER183(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
//
contract YieldDelegatingVaultEvent2 {
event NEWTREASURY741(address oldTreasury, address newTreasury); //inject NONSTANDARD NAMING
event NEWDELEGATEPERCENT315(uint256 oldDelegatePercent, uint256 newDelegatePercent); //inject NONSTANDARD NAMING
event NEWREWARDPERTOKEN257(uint256 oldRewardPerToken, uint256 newRewardPerToken); //inject NONSTANDARD NAMING
}
//
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 _ADD330(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
if (!_CONTAINS441(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 _REMOVE267(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 _CONTAINS441(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING
return set._indexes[value] != 0;
}
function _LENGTH266(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING
return set._values.length;
}
function _AT20(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 ADD236(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD330(set._inner, bytes32(uint256(value)));
}
function REMOVE884(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE267(set._inner, bytes32(uint256(value)));
}
function CONTAINS556(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS441(set._inner, bytes32(uint256(value)));
}
function LENGTH118(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH266(set._inner);
}
function AT34(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING
return address(uint256(_AT20(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
function ADD236(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD330(set._inner, bytes32(value));
}
function REMOVE884(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE267(set._inner, bytes32(value));
}
function CONTAINS556(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS441(set._inner, bytes32(value));
}
function LENGTH118(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH266(set._inner);
}
function AT34(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING
return uint256(_AT20(set._inner, index));
}
}
//
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_role567 = 0x00; //inject NONSTANDARD NAMING
event ROLEADMINCHANGED88(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); //inject NONSTANDARD NAMING
event ROLEGRANTED826(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING
event ROLEREVOKED185(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING
function HASROLE367(bytes32 role, address account) public view returns (bool) { //inject NONSTANDARD NAMING
return _roles[role].members.CONTAINS556(account);
}
function GETROLEMEMBERCOUNT938(bytes32 role) public view returns (uint256) { //inject NONSTANDARD NAMING
return _roles[role].members.LENGTH118();
}
function GETROLEMEMBER19(bytes32 role, uint256 index) public view returns (address) { //inject NONSTANDARD NAMING
return _roles[role].members.AT34(index);
}
function GETROLEADMIN235(bytes32 role) public view returns (bytes32) { //inject NONSTANDARD NAMING
return _roles[role].adminRole;
}
function GRANTROLE137(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(HASROLE367(_roles[role].adminRole, _MSGSENDER905()), "AccessControl: sender must be an admin to grant");
_GRANTROLE954(role, account);
}
function REVOKEROLE670(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(HASROLE367(_roles[role].adminRole, _MSGSENDER905()), "AccessControl: sender must be an admin to revoke");
_REVOKEROLE460(role, account);
}
function RENOUNCEROLE777(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(account == _MSGSENDER905(), "AccessControl: can only renounce roles for self");
_REVOKEROLE460(role, account);
}
function _SETUPROLE461(bytes32 role, address account) internal virtual { //inject NONSTANDARD NAMING
_GRANTROLE954(role, account);
}
function _SETROLEADMIN512(bytes32 role, bytes32 adminRole) internal virtual { //inject NONSTANDARD NAMING
emit ROLEADMINCHANGED88(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _GRANTROLE954(bytes32 role, address account) private { //inject NONSTANDARD NAMING
if (_roles[role].members.ADD236(account)) {
emit ROLEGRANTED826(role, account, _MSGSENDER905());
}
}
function _REVOKEROLE460(bytes32 role, address account) private { //inject NONSTANDARD NAMING
if (_roles[role].members.REMOVE884(account)) {
emit ROLEREVOKED185(role, account, _MSGSENDER905());
}
}
}
//
contract YDVRewardsDistributor is AccessControl, Ownable {
using SafeERC20 for IERC20;
using Address for address;
IERC20 public rewardToken;
address[] public ydvs;
bytes32 public constant ydv_rewards665 = keccak256("YDV_REWARDS"); //inject NONSTANDARD NAMING
constructor(address _rally) public {
rewardToken = IERC20(_rally);
_SETUPROLE461(default_admin_role567, msg.sender);
}
function TRANSFERREWARD486(uint256 _amount) external { //inject NONSTANDARD NAMING
require (HASROLE367(ydv_rewards665, msg.sender), "only ydv rewards");
rewardToken.SAFETRANSFER115(msg.sender, _amount);
}
function ADDYDV918(address _ydv) external ONLYOWNER378 { //inject NONSTANDARD NAMING
GRANTROLE137(ydv_rewards665, _ydv);
ydvs.push(_ydv);
}
function YDVSLENGTH403() external view returns (uint256) { //inject NONSTANDARD NAMING
return ydvs.length;
}
}
//
interface Vault {
function BALANCEOF1000(address) external view returns (uint256); //inject NONSTANDARD NAMING
function TOKEN783() external view returns (address); //inject NONSTANDARD NAMING
function CLAIMINSURANCE535() external; //inject NONSTANDARD NAMING
function GETPRICEPERFULLSHARE194() external view returns (uint256); //inject NONSTANDARD NAMING
function DEPOSIT941(uint) external; //inject NONSTANDARD NAMING
function WITHDRAW419(uint) external; //inject NONSTANDARD NAMING
}
//
contract YDVErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
REJECTION
}
enum FailureInfo {
SET_INDIVIDUAL_SOFT_CAP_CHECK,
SET_GLOBAL_SOFT_CAP_CHECK
}
event FAILURE308(uint error, uint info, uint detail); //inject NONSTANDARD NAMING
function FAIL273(Error err, FailureInfo info) internal returns (uint) { //inject NONSTANDARD NAMING
emit FAILURE308(uint(err), uint(info), 0);
return uint(err);
}
function FAILOPAQUE544(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { //inject NONSTANDARD NAMING
emit FAILURE308(uint(err), uint(info), opaqueError);
return uint(err);
}
}
//
contract RallyToken is ERC20 {
//15 billion fixed token supply with default 18 decimals
uint256 public constant token_supply159 = 15 * 10**9 * 10**18; //inject NONSTANDARD NAMING
constructor (
address _escrow
) public ERC20(
"Rally",
"RLY"
) {
_MINT985(_escrow, token_supply159);
}
}
//
contract NoMintLiquidityRewardPools is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of RLY
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accRallyPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accRallyPerShare` (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 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. RLYs to distribute per block.
uint256 lastRewardBlock; // Last block number that RLYs distribution occurs.
uint256 accRallyPerShare; // Accumulated RLYs per share, times 1e12. See below.
}
// The RALLY TOKEN!
RallyToken public rally;
// RLY tokens created per block.
uint256 public rallyPerBlock;
// 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 RLY mining starts.
uint256 public startBlock;
event DEPOSIT927(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAW385(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event EMERGENCYWITHDRAW903(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
constructor(
RallyToken _rally,
uint256 _rallyPerBlock,
uint256 _startBlock
) public {
rally = _rally;
rallyPerBlock = _rallyPerBlock;
startBlock = _startBlock;
}
function POOLLENGTH610() external view returns (uint256) { //inject NONSTANDARD NAMING
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function ADD236(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public ONLYOWNER378 { //inject NONSTANDARD NAMING
if (_withUpdate) {
MASSUPDATEPOOLS681();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.ADD236(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accRallyPerShare: 0
}));
}
// Update the given pool's RLY allocation point. Can only be called by the owner.
function SET138(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public ONLYOWNER378 { //inject NONSTANDARD NAMING
if (_withUpdate) {
MASSUPDATEPOOLS681();
}
totalAllocPoint = totalAllocPoint.SUB786(poolInfo[_pid].allocPoint).ADD236(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// update the rate at which RLY is allocated to rewards, can only be called by the owner
function SETRALLYPERBLOCK200(uint256 _rallyPerBlock) public ONLYOWNER378 { //inject NONSTANDARD NAMING
MASSUPDATEPOOLS681();
rallyPerBlock = _rallyPerBlock;
}
// View function to see pending RLYs on frontend.
function PENDINGRALLY232(uint256 _pid, address _user) external view returns (uint256) { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accRallyPerShare = pool.accRallyPerShare;
uint256 lpSupply = pool.lpToken.BALANCEOF1000(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = block.number.SUB786(pool.lastRewardBlock);
uint256 rallyReward = multiplier.MUL747(rallyPerBlock).MUL747(pool.allocPoint).DIV140(totalAllocPoint);
accRallyPerShare = accRallyPerShare.ADD236(rallyReward.MUL747(1e12).DIV140(lpSupply));
}
return user.amount.MUL747(accRallyPerShare).DIV140(1e12).SUB786(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function MASSUPDATEPOOLS681() public { //inject NONSTANDARD NAMING
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
UPDATEPOOL112(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
// No new RLY are minted, distribution is dependent on sufficient RLY tokens being sent to this contract
function UPDATEPOOL112(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.BALANCEOF1000(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = block.number.SUB786(pool.lastRewardBlock);
uint256 rallyReward = multiplier.MUL747(rallyPerBlock).MUL747(pool.allocPoint).DIV140(totalAllocPoint);
pool.accRallyPerShare = pool.accRallyPerShare.ADD236(rallyReward.MUL747(1e12).DIV140(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to pool for RLY allocation.
function DEPOSIT941(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
UPDATEPOOL112(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.MUL747(pool.accRallyPerShare).DIV140(1e12).SUB786(user.rewardDebt);
if(pending > 0) {
SAFERALLYTRANSFER520(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.SAFETRANSFERFROM287(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD236(_amount);
}
user.rewardDebt = user.amount.MUL747(pool.accRallyPerShare).DIV140(1e12);
emit DEPOSIT927(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from pool.
function WITHDRAW419(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
UPDATEPOOL112(_pid);
uint256 pending = user.amount.MUL747(pool.accRallyPerShare).DIV140(1e12).SUB786(user.rewardDebt);
if(pending > 0) {
SAFERALLYTRANSFER520(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.SUB786(_amount);
pool.lpToken.SAFETRANSFER115(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.MUL747(pool.accRallyPerShare).DIV140(1e12);
emit WITHDRAW385(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function EMERGENCYWITHDRAW757(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.SAFETRANSFER115(address(msg.sender), user.amount);
emit EMERGENCYWITHDRAW903(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe RLY transfer function, just in case pool does not have enough RLY; either rounding error or we're not supplying more rewards
function SAFERALLYTRANSFER520(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING
uint256 rallyBal = rally.BALANCEOF1000(address(this));
if (_amount > rallyBal) {
rally.TRANSFER912(_to, rallyBal);
} else {
rally.TRANSFER912(_to, _amount);
}
}
}
//
contract YieldDelegatingVaultStorage2 {
address public vault;
YDVRewardsDistributor rewards;
IERC20 public rally;
address public treasury;
IERC20 public token;
uint256 public delegatePercent;
mapping(address => uint256) public rewardDebt;
uint256 public totalDeposits;
uint256 public rewardPerToken;
uint256 public accRallyPerShare;
bool public lrEnabled;
uint256 public pid;
NoMintLiquidityRewardPools lrPools;
}
//
contract YieldDelegatingVault2 is ERC20, YieldDelegatingVaultStorage2, YieldDelegatingVaultEvent2, Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
constructor (
address _vault,
address _rewards,
address _treasury,
uint256 _delegatePercent,
uint256 _rewardPerToken
) public ERC20(
string(abi.encodePacked("rally delegating ", ERC20(Vault(_vault).TOKEN783()).NAME654())),
string(abi.encodePacked("rd", ERC20(Vault(_vault).TOKEN783()).SYMBOL381()))
) {
_SETUPDECIMALS502(ERC20(Vault(_vault).TOKEN783()).DECIMALS442());
token = IERC20(Vault(_vault).TOKEN783()); //token being deposited in the referenced vault
vault = _vault; //address of the vault we're proxying
rewards = YDVRewardsDistributor(_rewards);
rally = rewards.rewardToken();
treasury = _treasury;
delegatePercent = _delegatePercent;
rewardPerToken = _rewardPerToken;
totalDeposits = 0;
accRallyPerShare = 0;
lrEnabled = false;
}
function SETTREASURY672(address newTreasury) public ONLYOWNER378 { //inject NONSTANDARD NAMING
require(newTreasury != address(0), "treasure should be valid address");
address oldTreasury = treasury;
treasury = newTreasury;
emit NEWTREASURY741(oldTreasury, newTreasury);
}
function SETNEWREWARDPERTOKEN724(uint256 newRewardPerToken) public ONLYOWNER378 { //inject NONSTANDARD NAMING
uint256 oldRewardPerToken = rewardPerToken;
rewardPerToken = newRewardPerToken;
emit NEWREWARDPERTOKEN257(oldRewardPerToken, newRewardPerToken);
}
function EARNED974(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return BALANCEFORREWARDSCALC156(account).MUL747(accRallyPerShare).DIV140(1e12).SUB786(rewardDebt[account]);
}
function BALANCE265() public view returns (uint256) { //inject NONSTANDARD NAMING
return (IERC20(vault)).BALANCEOF1000(address(this)); //how many shares do we have in the vault we are delegating to
}
//for the purpose of rewards calculations, a user's balance is the total of what's in their wallet
//and what they have deposited in the rewards pool (if it's active).
//transfer restriction ensures accuracy of this sum
function BALANCEFORREWARDSCALC156(address account) internal view returns (uint256) { //inject NONSTANDARD NAMING
if (lrEnabled) {
(uint256 amount, ) = lrPools.userInfo(pid, account);
return BALANCEOF1000(account).ADD236(amount);
}
return BALANCEOF1000(account);
}
function DEPOSITALL490() external { //inject NONSTANDARD NAMING
DEPOSIT941(token.BALANCEOF1000(msg.sender));
}
function DEPOSIT941(uint256 _amount) public NONREENTRANT44 { //inject NONSTANDARD NAMING
uint256 pending = EARNED974(msg.sender);
if (pending > 0) {
SAFERALLYTRANSFER520(msg.sender, pending);
}
uint256 _pool = BALANCE265();
uint256 _before = token.BALANCEOF1000(address(this));
token.SAFETRANSFERFROM287(msg.sender, address(this), _amount);
uint256 _after = token.BALANCEOF1000(address(this));
_amount = _after.SUB786(_before);
totalDeposits = totalDeposits.ADD236(_amount);
token.APPROVE378(vault, _amount);
Vault(vault).DEPOSIT941(_amount);
uint256 _after_pool = BALANCE265();
uint256 _new_shares = _after_pool.SUB786(_pool); //new vault tokens representing my added vault shares
//translate vault shares into delegating vault shares
uint256 shares = 0;
if (TOTALSUPPLY709() == 0) {
shares = _new_shares;
} else {
shares = (_new_shares.MUL747(TOTALSUPPLY709())).DIV140(_pool);
}
_MINT985(msg.sender, shares);
rewardDebt[msg.sender] = BALANCEFORREWARDSCALC156(msg.sender).MUL747(accRallyPerShare).DIV140(1e12);
}
function DEPOSITYTOKEN556(uint256 _yamount) public NONREENTRANT44 { //inject NONSTANDARD NAMING
uint256 pending = EARNED974(msg.sender);
if (pending > 0) {
SAFERALLYTRANSFER520(msg.sender, pending);
}
uint256 _before = IERC20(vault).BALANCEOF1000(address(this));
IERC20(vault).SAFETRANSFERFROM287(msg.sender, address(this), _yamount);
uint256 _after = IERC20(vault).BALANCEOF1000(address(this));
_yamount = _after.SUB786(_before);
uint _underlyingAmount = _yamount.MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18);
totalDeposits = totalDeposits.ADD236(_underlyingAmount);
//translate vault shares into delegating vault shares
uint256 shares = 0;
if (TOTALSUPPLY709() == 0) {
shares = _yamount;
} else {
shares = (_yamount.MUL747(TOTALSUPPLY709())).DIV140(_before);
}
_MINT985(msg.sender, shares);
rewardDebt[msg.sender] = BALANCEFORREWARDSCALC156(msg.sender).MUL747(accRallyPerShare).DIV140(1e12);
}
function WITHDRAWALL908() external { //inject NONSTANDARD NAMING
WITHDRAW419(BALANCEOF1000(msg.sender));
}
function WITHDRAW419(uint256 _shares) public NONREENTRANT44 { //inject NONSTANDARD NAMING
uint256 pending = EARNED974(msg.sender);
if (pending > 0) {
SAFERALLYTRANSFER520(msg.sender, pending);
}
uint256 r = (BALANCE265().MUL747(_shares)).DIV140(TOTALSUPPLY709());
_BURN126(msg.sender, _shares);
SAFEREDUCETOTALDEPOSITS144(r.MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18));
rewardDebt[msg.sender] = BALANCEFORREWARDSCALC156(msg.sender).MUL747(accRallyPerShare).DIV140(1e12);
uint256 _before = token.BALANCEOF1000(address(this));
Vault(vault).WITHDRAW419(r);
uint256 _after = token.BALANCEOF1000(address(this));
uint256 toTransfer = _after.SUB786(_before);
token.SAFETRANSFER115(msg.sender, toTransfer);
}
//in case of rounding errors converting between vault tokens and underlying value
function SAFEREDUCETOTALDEPOSITS144(uint256 _amount) internal { //inject NONSTANDARD NAMING
if (_amount > totalDeposits) {
totalDeposits = 0;
} else {
totalDeposits = totalDeposits.SUB786(_amount);
}
}
function WITHDRAWYTOKEN466(uint256 _shares) public NONREENTRANT44 { //inject NONSTANDARD NAMING
uint256 pending = EARNED974(msg.sender);
if (pending > 0) {
SAFERALLYTRANSFER520(msg.sender, pending);
}
uint256 r = (BALANCE265().MUL747(_shares)).DIV140(TOTALSUPPLY709());
_BURN126(msg.sender, _shares);
rewardDebt[msg.sender] = BALANCEFORREWARDSCALC156(msg.sender).MUL747(accRallyPerShare).DIV140(1e12);
uint256 _amount = r.MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18);
SAFEREDUCETOTALDEPOSITS144(_amount);
IERC20(vault).SAFETRANSFER115(msg.sender, r);
}
// Safe RLY transfer function, just in case pool does not have enough RLY due to rounding error
function SAFERALLYTRANSFER520(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING
uint256 rallyBal = rally.BALANCEOF1000(address(this));
if (_amount > rallyBal) {
rally.TRANSFER912(_to, rallyBal);
} else {
rally.TRANSFER912(_to, _amount);
}
}
//how much are our shares of the underlying vault worth relative to the deposit value? returns value denominated in vault tokens
function AVAILABLEYIELD882() public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 totalValue = BALANCE265().MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18);
if (totalValue > totalDeposits) {
uint256 earnings = totalValue.SUB786(totalDeposits);
return earnings.MUL747(1e18).DIV140(Vault(vault).GETPRICEPERFULLSHARE194());
}
return 0;
}
//transfer accumulated yield to treasury, update totalDeposits to ensure availableYield following
//harvest is 0, and increase accumulated rally rewards
//harvest fails if we're unable to fund rewards
function HARVEST82() public ONLYOWNER378 { //inject NONSTANDARD NAMING
uint256 _availableYield = AVAILABLEYIELD882();
if (_availableYield > 0) {
uint256 rallyReward = _availableYield.MUL747(delegatePercent).DIV140(10000).MUL747(rewardPerToken).DIV140(1e18);
rewards.TRANSFERREWARD486(rallyReward);
IERC20(vault).SAFETRANSFER115(treasury, _availableYield.MUL747(delegatePercent).DIV140(10000));
accRallyPerShare = accRallyPerShare.ADD236(rallyReward.MUL747(1e12).DIV140(TOTALSUPPLY709()));
totalDeposits = BALANCE265().MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18);
}
}
//one way ticket and only callable once
function ENABLELIQUIDITYREWARDS505(address _lrPools, uint256 _pid) public ONLYOWNER378 { //inject NONSTANDARD NAMING
(IERC20 lpToken,,,) = NoMintLiquidityRewardPools(_lrPools).poolInfo(_pid);
require(address(lpToken) == address(this), "invalid liquidity rewards setup");
require(lrEnabled == false, "liquidity rewards already enabled");
lrEnabled = true;
lrPools = NoMintLiquidityRewardPools(_lrPools);
pid = _pid;
}
//override underlying _transfer implementation; YDV shares can only be transferred to/from the liquidity rewards pool
function _TRANSFER205(address sender, address recipient, uint256 amount) internal override { //inject NONSTANDARD NAMING
require(lrEnabled, "transfer rejected");
require(sender == address(lrPools) || recipient == address(lrPools), "transfer rejected");
super._TRANSFER205(sender, recipient, amount);
}
} | inject NONSTANDARD NAMING
| function APPROVE378(address spender, uint256 amount) public virtual override returns (bool) { | 12,852,111 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
14410,
3373,
3412,
6418,
28,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
13,
1071,
5024,
3849,
1135,
261,
6430,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.26;
// This is the smart contract for Simple FOMO
// A game theory based lottery that rewards the last entry with the 50% of the pot.
// Round 2 now also rewards the address/person that has the most entries with the other 50% of the pot
// This encourages players to enter early so they can take advantage of the lower entry cost.
// Modeled on the infamous Fomo3D but without its complexities, Simple FOMO has safeguards to reduce the chance
// a person will clog the blockchain to make them become the last entry and the winner.
contract Simple_FOMO_Round_2 {
// Administrator information
address public feeAddress; // This is the address of the person that collects the fees, nothing more, nothing less. It can be changed.
uint256 public feePercent = 2500; // This is the percent of the fee (2500 = 2.5%, 1 = 0.001%)
// Lotto information
uint256 public potSize = 0; // This is the size of the lottery pool in Wei
uint256 public entryCost = 1000000000000000; // This is the initial cost to enter the lottery pool (0.001 ETH)
uint256 constant entryCostStep = 5000000000000000; // This is the increase in the entry cost per 10 entries (0.005 ETH)
address public lastEntryAddress; // This is the address of the person who has entered the pool last
address public mostEntryAddress; // The address that has the most entries
uint256 public mostEntryCount = 0; // Represents the number of entries from the top entry address
uint256 public deadline; // This represents the initial deadline for the pool
uint256 constant gameDuration = 7; // This is the default amount of days the lottery will last for, can be extended with entries
uint256 public extensionTime = 600; // The default extension time per entry (600 seconds = 10 minutes)
// Extension time is increased by 0.5 seconds for each entry
// Player information
uint256 public totalEntries = 0; // The total amount of entries in the pool
mapping (address => uint256) private entryAmountList; // A list of entry amounts, mapped by each address (key)
constructor() public payable {
feeAddress = msg.sender; // Set the contract creator to the first feeAddress
lastEntryAddress = msg.sender;
mostEntryAddress = msg.sender;
potSize = msg.value;
deadline = now + gameDuration * 86400; // Set the game to end 7 days after lottery start
}
event ClaimedLotto(address _user, uint256 _amount); // Auxillary events
event MostEntries(address _user, uint256 _amount, uint256 _entries);
event AddedEntry(address _user, uint256 _amount, uint256 _entrycount);
event AddedNewParticipant(address _user);
event ChangedFeeAddress(address _newFeeAddress);
event FailedFeeSend(address _user, uint256 _amount);
// View function
function viewLottoDetails() public view returns (
uint256 _entryCost,
uint256 _potSize,
address _lastEntryAddress,
address _mostEntryAddress,
uint256 _mostEntryCount,
uint256 _deadline
) {
return (entryCost, potSize, lastEntryAddress, mostEntryAddress, mostEntryCount, deadline);
}
// Action functions
// Change contract fee address
function changeContractFeeAddress(address _newFeeAddress) public {
require (msg.sender == feeAddress); // Only the current feeAddress can change the feeAddress of the contract
feeAddress = _newFeeAddress; // Update the fee address
// Trigger event.
emit ChangedFeeAddress(_newFeeAddress);
}
// Withdraw from pool when time has expired
function claimLottery() public {
require (msg.sender == lastEntryAddress || msg.sender == mostEntryAddress); // Only the last person to enter or most entries can claim the lottery
uint256 currentTime = now; // Get the current time in seconds
uint256 claimTime = deadline + 300; // Add 5 minutes to the deadline, only after then can the lotto be claimed
require (currentTime > claimTime);
// Congrats, this person has won the lottery
require (potSize > 0); // Cannot claim an empty pot
uint256 totalTransferAmount = potSize; // The amount that is going to the winners
potSize = 0; // Set the potSize to zero before contacting the external address
uint256 transferAmountLastEntry = totalTransferAmount / 2; // This is the amount going to the last entry
uint256 transferAmountMostEntries = totalTransferAmount - transferAmountLastEntry; // The rest goes to the player with most entries
// Send to external accounts
// This method will only be used once, so make sure the receiving address is not a contract
bool sendok_most = mostEntryAddress.send(transferAmountMostEntries);
bool sendok_last = lastEntryAddress.send(transferAmountLastEntry);
// Trigger event.
if(sendok_last == true){
emit ClaimedLotto(lastEntryAddress, transferAmountLastEntry);
}
if(sendok_most == true){
emit MostEntries(mostEntryAddress, transferAmountMostEntries, mostEntryCount);
}
}
// Add entry to the pool
function addEntry() public payable {
require (msg.value == entryCost); // Entry must be equal to entry cost, not more or less
uint256 currentTime = now; // Get the current time in seconds
require (currentTime <= deadline); // Cannot submit an entry if the deadline has passed
// Add this player to the entry list if not already on it (new in Round 2)
uint256 entryAmount = entryAmountList[msg.sender];
if(entryAmount == 0){
// This is a new participant
emit AddedNewParticipant(msg.sender);
}
entryAmount++;
entryAmountList[msg.sender] = entryAmount; // Increase the entry count for this participant
//Now compare this entry to the most entries
if(entryAmount > mostEntryCount){
// This entry makes this user have the most entries
mostEntryCount = entryAmount;
mostEntryAddress = msg.sender;
}
// Entry is valid, now modify the pool based on it
uint256 feeAmount = (entryCost * feePercent) / 100000; // Calculate the usage fee
uint256 potAddition = entryCost - feeAmount; // This is the amount actually going into the pot
potSize = potSize + potAddition; // Add this amount to the pot
extensionTime = 600 + (totalEntries / 2); // The extension time increases as more entries are submitted
totalEntries = totalEntries + 1; // Increased the amount of entries
if(totalEntries % 10 == 0){
entryCost = entryCost + entryCostStep; // Increase the cost to enter every 10 entries
}
if(currentTime + extensionTime > deadline){ // Move the deadline if the extension time brings it beyond
deadline = currentTime + extensionTime;
}
lastEntryAddress = msg.sender; // Now this entry is the last address for now
//Pay a fee to the feeAddress
bool sentfee = feeAddress.send(feeAmount);
if(sentfee == false){
emit FailedFeeSend(feeAddress, feeAmount); // Create an event in case of fee sending failed, but don't stop registering the entry
}
// Trigger event.
emit AddedEntry(msg.sender, msg.value, entryAmountList[msg.sender]);
}
} | This is the percent of the fee (2500 = 2.5%, 1 = 0.001%)
| uint256 public feePercent = 2500; | 7,278,178 | [
1,
2503,
353,
326,
5551,
434,
326,
14036,
261,
2947,
713,
273,
576,
18,
25,
9,
16,
404,
273,
374,
18,
11664,
9,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
2254,
5034,
1071,
14036,
8410,
273,
6969,
713,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../abstract/MasterAware.sol";
import "../../interfaces/IPool.sol";
import "../cover/Quotation.sol";
import "../oracles/PriceFeedOracle.sol";
import "../token/NXMToken.sol";
import "../token/TokenController.sol";
import "./MCR.sol";
contract Pool is IPool, MasterAware, ReentrancyGuard {
using Address for address;
using SafeMath for uint;
using SafeERC20 for IERC20;
struct AssetData {
uint112 minAmount;
uint112 maxAmount;
uint32 lastSwapTime;
// 18 decimals of precision. 0.01% -> 0.0001 -> 1e14
uint maxSlippageRatio;
}
/* storage */
address[] public assets;
mapping(address => AssetData) public assetData;
// contracts
Quotation public quotation;
NXMToken public nxmToken;
TokenController public tokenController;
MCR public mcr;
// parameters
address public swapController;
uint public minPoolEth;
PriceFeedOracle public priceFeedOracle;
address public swapOperator;
/* constants */
address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint public constant MCR_RATIO_DECIMALS = 4;
uint public constant MAX_MCR_RATIO = 40000; // 400%
uint public constant MAX_BUY_SELL_MCR_ETH_FRACTION = 500; // 5%. 4 decimal points
uint internal constant CONSTANT_C = 5800000;
uint internal constant CONSTANT_A = 1028 * 1e13;
uint internal constant TOKEN_EXPONENT = 4;
/* events */
event Payout(address indexed to, address indexed asset, uint amount);
event NXMSold (address indexed member, uint nxmIn, uint ethOut);
event NXMBought (address indexed member, uint ethIn, uint nxmOut);
event Swapped(address indexed fromAsset, address indexed toAsset, uint amountIn, uint amountOut);
/* logic */
modifier onlySwapOperator {
require(msg.sender == swapOperator, "Pool: not swapOperator");
_;
}
constructor (
address[] memory _assets,
uint112[] memory _minAmounts,
uint112[] memory _maxAmounts,
uint[] memory _maxSlippageRatios,
address _master,
address _priceOracle,
address _swapOperator
) public {
require(_assets.length == _minAmounts.length, "Pool: length mismatch");
require(_assets.length == _maxAmounts.length, "Pool: length mismatch");
require(_assets.length == _maxSlippageRatios.length, "Pool: length mismatch");
for (uint i = 0; i < _assets.length; i++) {
address asset = _assets[i];
require(asset != address(0), "Pool: asset is zero address");
require(_maxAmounts[i] >= _minAmounts[i], "Pool: max < min");
require(_maxSlippageRatios[i] <= 1 ether, "Pool: max < min");
assets.push(asset);
assetData[asset].minAmount = _minAmounts[i];
assetData[asset].maxAmount = _maxAmounts[i];
assetData[asset].maxSlippageRatio = _maxSlippageRatios[i];
}
master = INXMMaster(_master);
priceFeedOracle = PriceFeedOracle(_priceOracle);
swapOperator = _swapOperator;
}
// fallback function
function() external payable {}
// for legacy Pool1 upgrade compatibility
function sendEther() external payable {}
/**
* @dev Calculates total value of all pool assets in ether
*/
function getPoolValueInEth() public view returns (uint) {
uint total = address(this).balance;
for (uint i = 0; i < assets.length; i++) {
address assetAddress = assets[i];
IERC20 token = IERC20(assetAddress);
uint rate = priceFeedOracle.getAssetToEthRate(assetAddress);
require(rate > 0, "Pool: zero rate");
uint assetBalance = token.balanceOf(address(this));
uint assetValue = assetBalance.mul(rate).div(1e18);
total = total.add(assetValue);
}
return total;
}
/* asset related functions */
function getAssets() external view returns (address[] memory) {
return assets;
}
function getAssetDetails(address _asset) external view returns (
uint112 min,
uint112 max,
uint32 lastAssetSwapTime,
uint maxSlippageRatio
) {
AssetData memory data = assetData[_asset];
return (data.minAmount, data.maxAmount, data.lastSwapTime, data.maxSlippageRatio);
}
function addAsset(
address _asset,
uint112 _min,
uint112 _max,
uint _maxSlippageRatio
) external onlyGovernance {
require(_asset != address(0), "Pool: asset is zero address");
require(_max >= _min, "Pool: max < min");
require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1");
for (uint i = 0; i < assets.length; i++) {
require(_asset != assets[i], "Pool: asset exists");
}
assets.push(_asset);
assetData[_asset] = AssetData(_min, _max, 0, _maxSlippageRatio);
}
function removeAsset(address _asset) external onlyGovernance {
for (uint i = 0; i < assets.length; i++) {
if (_asset != assets[i]) {
continue;
}
delete assetData[_asset];
assets[i] = assets[assets.length - 1];
assets.pop();
return;
}
revert("Pool: asset not found");
}
function setAssetDetails(
address _asset,
uint112 _min,
uint112 _max,
uint _maxSlippageRatio
) external onlyGovernance {
require(_min <= _max, "Pool: min > max");
require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1");
for (uint i = 0; i < assets.length; i++) {
if (_asset != assets[i]) {
continue;
}
assetData[_asset].minAmount = _min;
assetData[_asset].maxAmount = _max;
assetData[_asset].maxSlippageRatio = _maxSlippageRatio;
return;
}
revert("Pool: asset not found");
}
/* claim related functions */
/**
* @dev Execute the payout in case a claim is accepted
* @param asset token address or 0xEee...EEeE for ether
* @param payoutAddress send funds to this address
* @param amount amount to send
*/
function sendClaimPayout (
address asset,
address payable payoutAddress,
uint amount
) external onlyInternal nonReentrant returns (bool success) {
bool ok;
if (asset == ETH) {
// solhint-disable-next-line avoid-low-level-calls
(ok, /* data */) = payoutAddress.call.value(amount)("");
} else {
ok = _safeTokenTransfer(asset, payoutAddress, amount);
}
if (ok) {
emit Payout(payoutAddress, asset, amount);
}
return ok;
}
/**
* @dev safeTransfer implementation that does not revert
* @param tokenAddress ERC20 address
* @param to destination
* @param value amount to send
* @return success true if the transfer was successfull
*/
function _safeTokenTransfer (
address tokenAddress,
address to,
uint256 value
) internal returns (bool) {
// token address is not a contract
if (!tokenAddress.isContract()) {
return false;
}
IERC20 token = IERC20(tokenAddress);
bytes memory data = abi.encodeWithSelector(token.transfer.selector, to, value);
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = tokenAddress.call(data);
// low-level call failed/reverted
if (!success) {
return false;
}
// tokens that don't have return data
if (returndata.length == 0) {
return true;
}
// tokens that have return data will return a bool
return abi.decode(returndata, (bool));
}
/* pool lifecycle functions */
function transferAsset(
address asset,
address payable destination,
uint amount
) external onlyGovernance nonReentrant {
require(assetData[asset].maxAmount == 0, "Pool: max not zero");
require(destination != address(0), "Pool: dest zero");
IERC20 token = IERC20(asset);
uint balance = token.balanceOf(address(this));
uint transferableAmount = amount > balance ? balance : amount;
token.safeTransfer(destination, transferableAmount);
}
function upgradeCapitalPool(address payable newPoolAddress) external onlyMaster nonReentrant {
// transfer ether
uint ethBalance = address(this).balance;
(bool ok, /* data */) = newPoolAddress.call.value(ethBalance)("");
require(ok, "Pool: transfer failed");
// transfer assets
for (uint i = 0; i < assets.length; i++) {
IERC20 token = IERC20(assets[i]);
uint tokenBalance = token.balanceOf(address(this));
token.safeTransfer(newPoolAddress, tokenBalance);
}
}
/**
* @dev Update dependent contract address
* @dev Implements MasterAware interface function
*/
function changeDependentContractAddress() public {
nxmToken = NXMToken(master.tokenAddress());
tokenController = TokenController(master.getLatestAddress("TC"));
quotation = Quotation(master.getLatestAddress("QT"));
mcr = MCR(master.getLatestAddress("MC"));
}
/* cover purchase functions */
/// @dev Enables user to purchase cover with funding in ETH.
/// @param smartCAdd Smart Contract Address
function makeCoverBegin(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public payable onlyMember whenNotPaused {
require(coverCurr == "ETH", "Pool: Unexpected asset type");
require(msg.value == coverDetails[1], "Pool: ETH amount does not match premium");
quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
/**
* @dev Enables user to purchase cover via currency asset eg DAI
*/
function makeCoverUsingCA(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public onlyMember whenNotPaused {
require(coverCurr != "ETH", "Pool: Unexpected asset type");
quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
function transferAssetFrom (address asset, address from, uint amount) public onlyInternal whenNotPaused {
IERC20 token = IERC20(asset);
token.safeTransferFrom(from, address(this), amount);
}
function transferAssetToSwapOperator (address asset, uint amount) public onlySwapOperator nonReentrant whenNotPaused {
if (asset == ETH) {
(bool ok, /* data */) = swapOperator.call.value(amount)("");
require(ok, "Pool: Eth transfer failed");
return;
}
IERC20 token = IERC20(asset);
token.safeTransfer(swapOperator, amount);
}
function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) public onlySwapOperator whenNotPaused {
assetData[asset].lastSwapTime = lastSwapTime;
}
/* token sale functions */
/**
* @dev (DEPRECATED, use sellTokens function instead) Allows selling of NXM for ether.
* Seller first needs to give this contract allowance to
* transfer/burn tokens in the NXMToken contract
* @param _amount Amount of NXM to sell
* @return success returns true on successfull sale
*/
function sellNXMTokens(uint _amount) public onlyMember whenNotPaused returns (bool success) {
sellNXM(_amount, 0);
return true;
}
/**
* @dev (DEPRECATED, use calculateNXMForEth function instead) Returns the amount of wei a seller will get for selling NXM
* @param amount Amount of NXM to sell
* @return weiToPay Amount of wei the seller will get
*/
function getWei(uint amount) external view returns (uint weiToPay) {
return getEthForNXM(amount);
}
/**
* @dev Buys NXM tokens with ETH.
* @param minTokensOut Minimum amount of tokens to be bought. Revert if boughtTokens falls below this number.
* @return boughtTokens number of bought tokens.
*/
function buyNXM(uint minTokensOut) public payable onlyMember whenNotPaused {
uint ethIn = msg.value;
require(ethIn > 0, "Pool: ethIn > 0");
uint totalAssetValue = getPoolValueInEth().sub(ethIn);
uint mcrEth = mcr.getMCR();
uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth);
require(mcrRatio <= MAX_MCR_RATIO, "Pool: Cannot purchase if MCR% > 400%");
uint tokensOut = calculateNXMForEth(ethIn, totalAssetValue, mcrEth);
require(tokensOut >= minTokensOut, "Pool: tokensOut is less than minTokensOut");
tokenController.mint(msg.sender, tokensOut);
// evaluate the new MCR for the current asset value including the ETH paid in
mcr.updateMCRInternal(totalAssetValue.add(ethIn), false);
emit NXMBought(msg.sender, ethIn, tokensOut);
}
/**
* @dev Sell NXM tokens and receive ETH.
* @param tokenAmount Amount of tokens to sell.
* @param minEthOut Minimum amount of ETH to be received. Revert if ethOut falls below this number.
* @return ethOut amount of ETH received in exchange for the tokens.
*/
function sellNXM(uint tokenAmount, uint minEthOut) public onlyMember nonReentrant whenNotPaused {
require(nxmToken.balanceOf(msg.sender) >= tokenAmount, "Pool: Not enough balance");
require(nxmToken.isLockedForMV(msg.sender) <= now, "Pool: NXM tokens are locked for voting");
uint currentTotalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
uint ethOut = calculateEthForNXM(tokenAmount, currentTotalAssetValue, mcrEth);
require(currentTotalAssetValue.sub(ethOut) >= mcrEth, "Pool: MCR% cannot fall below 100%");
require(ethOut >= minEthOut, "Pool: ethOut < minEthOut");
tokenController.burnFrom(msg.sender, tokenAmount);
(bool ok, /* data */) = msg.sender.call.value(ethOut)("");
require(ok, "Pool: Sell transfer failed");
// evaluate the new MCR for the current asset value excluding the paid out ETH
mcr.updateMCRInternal(currentTotalAssetValue.sub(ethOut), false);
emit NXMSold(msg.sender, tokenAmount, ethOut);
}
/**
* @dev Get value in tokens for an ethAmount purchase.
* @param ethAmount amount of ETH used for buying.
* @return tokenValue tokens obtained by buying worth of ethAmount
*/
function getNXMForEth(
uint ethAmount
) public view returns (uint) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateNXMForEth(ethAmount, totalAssetValue, mcrEth);
}
function calculateNXMForEth(
uint ethAmount,
uint currentTotalAssetValue,
uint mcrEth
) public pure returns (uint) {
require(
ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS),
"Pool: Purchases worth higher than 5% of MCReth are not allowed"
);
/*
The price formula is:
P(V) = A + MCReth / C * MCR% ^ 4
where MCR% = V / MCReth
P(V) = A + 1 / (C * MCReth ^ 3) * V ^ 4
To compute the number of tokens issued we can integrate with respect to V the following:
ΔT = ΔV / P(V)
which assumes that for an infinitesimally small change in locked value V price is constant and we
get an infinitesimally change in token supply ΔT.
This is not computable on-chain, below we use an approximation that works well assuming
* MCR% stays within [100%, 400%]
* ethAmount <= 5% * MCReth
Use a simplified formula excluding the constant A price offset to compute the amount of tokens to be minted.
AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4
AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4
For a very small variation in tokens ΔT, we have, ΔT = ΔV / P(V), to get total T we integrate with respect to V.
adjustedTokenAmount = ∫ (dV / AdjustedP(V)) from V0 (currentTotalAssetValue) to V1 (nextTotalAssetValue)
adjustedTokenAmount = ∫ ((C * MCReth ^ 3) / V ^ 4 * dV) from V0 to V1
Evaluating the above using the antiderivative of the function we get:
adjustedTokenAmount = - MCReth ^ 3 * C / (3 * V1 ^3) + MCReth * C /(3 * V0 ^ 3)
*/
if (currentTotalAssetValue == 0 || mcrEth.div(currentTotalAssetValue) > 1e12) {
/*
If the currentTotalAssetValue = 0, adjustedTokenPrice approaches 0. Therefore we can assume the price is A.
If currentTotalAssetValue is far smaller than mcrEth, MCR% approaches 0, let the price be A (baseline price).
This avoids overflow in the calculateIntegralAtPoint computation.
This approximation is safe from arbitrage since at MCR% < 100% no sells are possible.
*/
uint tokenPrice = CONSTANT_A;
return ethAmount.mul(1e18).div(tokenPrice);
}
// MCReth * C /(3 * V0 ^ 3)
uint point0 = calculateIntegralAtPoint(currentTotalAssetValue, mcrEth);
// MCReth * C / (3 * V1 ^3)
uint nextTotalAssetValue = currentTotalAssetValue.add(ethAmount);
uint point1 = calculateIntegralAtPoint(nextTotalAssetValue, mcrEth);
uint adjustedTokenAmount = point0.sub(point1);
/*
Compute a preliminary adjustedTokenPrice for the minted tokens based on the adjustedTokenAmount above,
and to that add the A constant (the price offset previously removed in the adjusted Price formula)
to obtain the finalPrice and ultimately the tokenValue based on the finalPrice.
adjustedPrice = ethAmount / adjustedTokenAmount
finalPrice = adjustedPrice + A
tokenValue = ethAmount / finalPrice
*/
// ethAmount is multiplied by 1e18 to cancel out the multiplication factor of 1e18 of the adjustedTokenAmount
uint adjustedTokenPrice = ethAmount.mul(1e18).div(adjustedTokenAmount);
uint tokenPrice = adjustedTokenPrice.add(CONSTANT_A);
return ethAmount.mul(1e18).div(tokenPrice);
}
/**
* @dev integral(V) = MCReth ^ 3 * C / (3 * V ^ 3) * 1e18
* computation result is multiplied by 1e18 to allow for a precision of 18 decimals.
* NOTE: omits the minus sign of the correct integral to use a uint result type for simplicity
* WARNING: this low-level function should be called from a contract which checks that
* mcrEth / assetValue < 1e17 (no overflow) and assetValue != 0
*/
function calculateIntegralAtPoint(
uint assetValue,
uint mcrEth
) internal pure returns (uint) {
return CONSTANT_C
.mul(1e18)
.div(3)
.mul(mcrEth).div(assetValue)
.mul(mcrEth).div(assetValue)
.mul(mcrEth).div(assetValue);
}
function getEthForNXM(uint nxmAmount) public view returns (uint ethAmount) {
uint currentTotalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateEthForNXM(nxmAmount, currentTotalAssetValue, mcrEth);
}
/**
* @dev Computes token sell value for a tokenAmount in ETH with a sell spread of 2.5%.
* for values in ETH of the sale <= 1% * MCReth the sell spread is very close to the exact value of 2.5%.
* for values higher than that sell spread may exceed 2.5%
* (The higher amount being sold at any given time the higher the spread)
*/
function calculateEthForNXM(
uint nxmAmount,
uint currentTotalAssetValue,
uint mcrEth
) public pure returns (uint) {
// Step 1. Calculate spot price at current values and amount of ETH if tokens are sold at that price
uint spotPrice0 = calculateTokenSpotPrice(currentTotalAssetValue, mcrEth);
uint spotEthAmount = nxmAmount.mul(spotPrice0).div(1e18);
// Step 2. Calculate spot price using V = currentTotalAssetValue - spotEthAmount from step 1
uint totalValuePostSpotPriceSell = currentTotalAssetValue.sub(spotEthAmount);
uint spotPrice1 = calculateTokenSpotPrice(totalValuePostSpotPriceSell, mcrEth);
// Step 3. Min [average[Price(0), Price(1)] x ( 1 - Sell Spread), Price(1) ]
// Sell Spread = 2.5%
uint averagePriceWithSpread = spotPrice0.add(spotPrice1).div(2).mul(975).div(1000);
uint finalPrice = averagePriceWithSpread < spotPrice1 ? averagePriceWithSpread : spotPrice1;
uint ethAmount = finalPrice.mul(nxmAmount).div(1e18);
require(
ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS),
"Pool: Sales worth more than 5% of MCReth are not allowed"
);
return ethAmount;
}
function calculateMCRRatio(uint totalAssetValue, uint mcrEth) public pure returns (uint) {
return totalAssetValue.mul(10 ** MCR_RATIO_DECIMALS).div(mcrEth);
}
/**
* @dev Calculates token price in ETH 1 NXM token. TokenPrice = A + (MCReth / C) * MCR%^4
*/
function calculateTokenSpotPrice(uint totalAssetValue, uint mcrEth) public pure returns (uint tokenPrice) {
uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth);
uint precisionDecimals = 10 ** TOKEN_EXPONENT.mul(MCR_RATIO_DECIMALS);
return mcrEth
.mul(mcrRatio ** TOKEN_EXPONENT)
.div(CONSTANT_C)
.div(precisionDecimals)
.add(CONSTANT_A);
}
/**
* @dev Returns the NXM price in a given asset
* @param asset Asset name.
*/
function getTokenPrice(address asset) public view returns (uint tokenPrice) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
uint tokenSpotPriceEth = calculateTokenSpotPrice(totalAssetValue, mcrEth);
return priceFeedOracle.getAssetForEth(asset, tokenSpotPriceEth);
}
function getMCRRatio() public view returns (uint) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateMCRRatio(totalAssetValue, mcrEth);
}
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "MIN_ETH") {
minPoolEth = value;
return;
}
revert("Pool: unknown parameter");
}
function updateAddressParameters(bytes8 code, address value) external onlyGovernance {
if (code == "SWP_OP") {
swapOperator = value;
return;
}
if (code == "PRC_FEED") {
priceFeedOracle = PriceFeedOracle(value);
return;
}
revert("Pool: unknown parameter");
}
}
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 Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/*
Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
*/
pragma solidity ^0.5.0;
import "./INXMMaster.sol";
contract MasterAware {
INXMMaster public master;
modifier onlyMember {
require(master.isMember(msg.sender), "Caller is not a member");
_;
}
modifier onlyInternal {
require(master.isInternal(msg.sender), "Caller is not an internal contract");
_;
}
modifier onlyMaster {
if (address(master) != address(0)) {
require(address(master) == msg.sender, "Not master");
}
_;
}
modifier onlyGovernance {
require(
master.checkIsAuthToGoverned(msg.sender),
"Caller is not authorized to govern"
);
_;
}
modifier whenPaused {
require(master.isPause(), "System is not paused");
_;
}
modifier whenNotPaused {
require(!master.isPause(), "System is paused");
_;
}
function changeDependentContractAddress() external;
function changeMasterAddress(address masterAddress) public onlyMaster {
master = INXMMaster(masterAddress);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IPool {
function transferAssetToSwapOperator(address asset, uint amount) external;
function getAssetDetails(address _asset) external view returns (
uint112 min,
uint112 max,
uint32 lastAssetSwapTime,
uint maxSlippageRatio
);
function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) external;
function minPoolEth() external returns (uint);
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../../abstract/MasterAware.sol";
import "../capital/Pool.sol";
import "../claims/ClaimsReward.sol";
import "../claims/Incidents.sol";
import "../token/TokenController.sol";
import "../token/TokenData.sol";
import "./QuotationData.sol";
contract Quotation is MasterAware, ReentrancyGuard {
using SafeMath for uint;
ClaimsReward public cr;
Pool public pool;
IPooledStaking public pooledStaking;
QuotationData public qd;
TokenController public tc;
TokenData public td;
Incidents public incidents;
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
cr = ClaimsReward(master.getLatestAddress("CR"));
pool = Pool(master.getLatestAddress("P1"));
pooledStaking = IPooledStaking(master.getLatestAddress("PS"));
qd = QuotationData(master.getLatestAddress("QD"));
tc = TokenController(master.getLatestAddress("TC"));
td = TokenData(master.getLatestAddress("TD"));
incidents = Incidents(master.getLatestAddress("IC"));
}
// solhint-disable-next-line no-empty-blocks
function sendEther() public payable {}
/**
* @dev Expires a cover after a set period of time and changes the status of the cover
* @dev Reduces the total and contract sum assured
* @param coverId Cover Id.
*/
function expireCover(uint coverId) external {
uint expirationDate = qd.getValidityOfCover(coverId);
require(expirationDate < now, "Quotation: cover is not due to expire");
uint coverStatus = qd.getCoverStatusNo(coverId);
require(coverStatus != uint(QuotationData.CoverStatus.CoverExpired), "Quotation: cover already expired");
(/* claim count */, bool hasOpenClaim, /* accepted */) = tc.coverInfo(coverId);
require(!hasOpenClaim, "Quotation: cover has an open claim");
if (coverStatus != uint(QuotationData.CoverStatus.ClaimAccepted)) {
(,, address contractAddress, bytes4 currency, uint amount,) = qd.getCoverDetailsByCoverID1(coverId);
qd.subFromTotalSumAssured(currency, amount);
qd.subFromTotalSumAssuredSC(contractAddress, currency, amount);
}
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.CoverExpired));
}
function withdrawCoverNote(address coverOwner, uint[] calldata coverIds, uint[] calldata reasonIndexes) external {
uint gracePeriod = tc.claimSubmissionGracePeriod();
for (uint i = 0; i < coverIds.length; i++) {
uint expirationDate = qd.getValidityOfCover(coverIds[i]);
require(expirationDate.add(gracePeriod) < now, "Quotation: cannot withdraw before grace period expiration");
}
tc.withdrawCoverNote(coverOwner, coverIds, reasonIndexes);
}
function getWithdrawableCoverNoteCoverIds(
address coverOwner
) public view returns (
uint[] memory expiredCoverIds,
bytes32[] memory lockReasons
) {
uint[] memory coverIds = qd.getAllCoversOfUser(coverOwner);
uint[] memory expiredIdsQueue = new uint[](coverIds.length);
uint gracePeriod = tc.claimSubmissionGracePeriod();
uint expiredQueueLength = 0;
for (uint i = 0; i < coverIds.length; i++) {
uint coverExpirationDate = qd.getValidityOfCover(coverIds[i]);
uint gracePeriodExpirationDate = coverExpirationDate.add(gracePeriod);
(/* claimCount */, bool hasOpenClaim, /* hasAcceptedClaim */) = tc.coverInfo(coverIds[i]);
if (!hasOpenClaim && gracePeriodExpirationDate < now) {
expiredIdsQueue[expiredQueueLength] = coverIds[i];
expiredQueueLength++;
}
}
expiredCoverIds = new uint[](expiredQueueLength);
lockReasons = new bytes32[](expiredQueueLength);
for (uint i = 0; i < expiredQueueLength; i++) {
expiredCoverIds[i] = expiredIdsQueue[i];
lockReasons[i] = keccak256(abi.encodePacked("CN", coverOwner, expiredIdsQueue[i]));
}
}
function getWithdrawableCoverNotesAmount(address coverOwner) external view returns (uint) {
uint withdrawableAmount;
bytes32[] memory lockReasons;
(/*expiredCoverIds*/, lockReasons) = getWithdrawableCoverNoteCoverIds(coverOwner);
for (uint i = 0; i < lockReasons.length; i++) {
uint coverNoteAmount = tc.tokensLocked(coverOwner, lockReasons[i]);
withdrawableAmount = withdrawableAmount.add(coverNoteAmount);
}
return withdrawableAmount;
}
/**
* @dev Makes Cover funded via NXM tokens.
* @param smartCAdd Smart Contract Address
*/
function makeCoverUsingNXMTokens(
uint[] calldata coverDetails,
uint16 coverPeriod,
bytes4 coverCurr,
address smartCAdd,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyMember whenNotPaused {
tc.burnFrom(msg.sender, coverDetails[2]); // needs allowance
_verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s, true);
}
/**
* @dev Verifies cover details signed off chain.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public onlyInternal {
_verifyCoverDetails(
from,
scAddress,
coverCurr,
coverDetails,
coverPeriod,
_v,
_r,
_s,
false
);
}
/**
* @dev Verifies signature.
* @param coverDetails details related to cover.
* @param coverPeriod validity of cover.
* @param contractAddress smart contract address.
* @param _v argument from vrs hash.
* @param _r argument from vrs hash.
* @param _s argument from vrs hash.
*/
function verifySignature(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 currency,
address contractAddress,
uint8 _v,
bytes32 _r,
bytes32 _s
) public view returns (bool) {
require(contractAddress != address(0));
bytes32 hash = getOrderHash(coverDetails, coverPeriod, currency, contractAddress);
return isValidSignature(hash, _v, _r, _s);
}
/**
* @dev Gets order hash for given cover details.
* @param coverDetails details realted to cover.
* @param coverPeriod validity of cover.
* @param contractAddress smart contract address.
*/
function getOrderHash(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 currency,
address contractAddress
) public view returns (bytes32) {
return keccak256(
abi.encodePacked(
coverDetails[0],
currency,
coverPeriod,
contractAddress,
coverDetails[1],
coverDetails[2],
coverDetails[3],
coverDetails[4],
address(this)
)
);
}
/**
* @dev Verifies signature.
* @param hash order hash
* @param v argument from vrs hash.
* @param r argument from vrs hash.
* @param s argument from vrs hash.
*/
function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns (bool) {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
address a = ecrecover(prefixedHash, v, r, s);
return (a == qd.getAuthQuoteEngine());
}
/**
* @dev Creates cover of the quotation, changes the status of the quotation ,
* updates the total sum assured and locks the tokens of the cover against a quote.
* @param from Quote member Ethereum address.
*/
function _makeCover(//solhint-disable-line
address payable from,
address contractAddress,
bytes4 coverCurrency,
uint[] memory coverDetails,
uint16 coverPeriod
) internal {
address underlyingToken = incidents.underlyingToken(contractAddress);
if (underlyingToken != address(0)) {
address coverAsset = cr.getCurrencyAssetAddress(coverCurrency);
require(coverAsset == underlyingToken, "Quotation: Unsupported cover asset for this product");
}
uint cid = qd.getCoverLength();
qd.addCover(
coverPeriod,
coverDetails[0],
from,
coverCurrency,
contractAddress,
coverDetails[1],
coverDetails[2]
);
uint coverNoteAmount = coverDetails[2].mul(qd.tokensRetained()).div(100);
if (underlyingToken == address(0)) {
uint gracePeriod = tc.claimSubmissionGracePeriod();
uint claimSubmissionPeriod = uint(coverPeriod).mul(1 days).add(gracePeriod);
bytes32 reason = keccak256(abi.encodePacked("CN", from, cid));
// mint and lock cover note
td.setDepositCNAmount(cid, coverNoteAmount);
tc.mintCoverNote(from, reason, coverNoteAmount, claimSubmissionPeriod);
} else {
// minted directly to member's wallet
tc.mint(from, coverNoteAmount);
}
qd.addInTotalSumAssured(coverCurrency, coverDetails[0]);
qd.addInTotalSumAssuredSC(contractAddress, coverCurrency, coverDetails[0]);
uint coverPremiumInNXM = coverDetails[2];
uint stakersRewardPercentage = td.stakerCommissionPer();
uint rewardValue = coverPremiumInNXM.mul(stakersRewardPercentage).div(100);
pooledStaking.accumulateReward(contractAddress, rewardValue);
}
/**
* @dev Makes a cover.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function _verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s,
bool isNXM
) internal {
require(coverDetails[3] > now, "Quotation: Quote has expired");
require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds");
require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used");
qd.setTimestampRepeated(coverDetails[4]);
address asset = cr.getCurrencyAssetAddress(coverCurr);
if (coverCurr != "ETH" && !isNXM) {
pool.transferAssetFrom(asset, from, coverDetails[1]);
}
require(verifySignature(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s), "Quotation: signature mismatch");
_makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod);
}
function createCover(
address payable from,
address scAddress,
bytes4 currency,
uint[] calldata coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyInternal {
require(coverDetails[3] > now, "Quotation: Quote has expired");
require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds");
require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used");
qd.setTimestampRepeated(coverDetails[4]);
require(verifySignature(coverDetails, coverPeriod, currency, scAddress, _v, _r, _s), "Quotation: signature mismatch");
_makeCover(from, scAddress, currency, coverDetails, coverPeriod);
}
// referenced in master, keeping for now
// solhint-disable-next-line no-empty-blocks
function transferAssetsToNewContract(address) external pure {}
function freeUpHeldCovers() external nonReentrant {
IERC20 dai = IERC20(cr.getCurrencyAssetAddress("DAI"));
uint membershipFee = td.joiningFee();
uint lastCoverId = 106;
for (uint id = 1; id <= lastCoverId; id++) {
if (qd.holdedCoverIDStatus(id) != uint(QuotationData.HCIDStatus.kycPending)) {
continue;
}
(/*id*/, /*sc*/, bytes4 currency, /*period*/) = qd.getHoldedCoverDetailsByID1(id);
(/*id*/, address payable userAddress, uint[] memory coverDetails) = qd.getHoldedCoverDetailsByID2(id);
uint refundedETH = membershipFee;
uint coverPremium = coverDetails[1];
if (qd.refundEligible(userAddress)) {
qd.setRefundEligible(userAddress, false);
}
qd.setHoldedCoverIDStatus(id, uint(QuotationData.HCIDStatus.kycFailedOrRefunded));
if (currency == "ETH") {
refundedETH = refundedETH.add(coverPremium);
} else {
require(dai.transfer(userAddress, coverPremium), "Quotation: DAI refund transfer failed");
}
userAddress.transfer(refundedETH);
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
interface Aggregator {
function latestAnswer() external view returns (int);
}
contract PriceFeedOracle {
using SafeMath for uint;
mapping(address => address) public aggregators;
address public daiAddress;
address public stETH;
address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor (
address _daiAggregator,
address _daiAddress,
address _stEthAddress
) public {
aggregators[_daiAddress] = _daiAggregator;
daiAddress = _daiAddress;
stETH = _stEthAddress;
}
/**
* @dev Returns the amount of ether in wei that are equivalent to 1 unit (10 ** decimals) of asset
* @param asset quoted currency
* @return price in ether
*/
function getAssetToEthRate(address asset) public view returns (uint) {
if (asset == ETH || asset == stETH) {
return 1 ether;
}
address aggregatorAddress = aggregators[asset];
if (aggregatorAddress == address(0)) {
revert("PriceFeedOracle: Oracle asset not found");
}
int rate = Aggregator(aggregatorAddress).latestAnswer();
require(rate > 0, "PriceFeedOracle: Rate must be > 0");
return uint(rate);
}
/**
* @dev Returns the amount of currency that is equivalent to ethIn amount of ether.
* @param asset quoted Supported values: ["DAI", "ETH"]
* @param ethIn amount of ether to be converted to the currency
* @return price in ether
*/
function getAssetForEth(address asset, uint ethIn) external view returns (uint) {
if (asset == daiAddress) {
return ethIn.mul(1e18).div(getAssetToEthRate(daiAddress));
}
if (asset == ETH || asset == stETH) {
return ethIn;
}
revert("PriceFeedOracle: Unknown asset");
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "./external/OZIERC20.sol";
import "./external/OZSafeMath.sol";
contract NXMToken is OZIERC20 {
using OZSafeMath for uint256;
event WhiteListed(address indexed member);
event BlackListed(address indexed member);
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowed;
mapping(address => bool) public whiteListed;
mapping(address => uint) public isLockedForMV;
uint256 private _totalSupply;
string public name = "NXM";
string public symbol = "NXM";
uint8 public decimals = 18;
address public operator;
modifier canTransfer(address _to) {
require(whiteListed[_to]);
_;
}
modifier onlyOperator() {
if (operator != address(0))
require(msg.sender == operator);
_;
}
constructor(address _founderAddress, uint _initialSupply) public {
_mint(_founderAddress, _initialSupply);
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_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 decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Adds a user to whitelist
* @param _member address to add to whitelist
*/
function addToWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = true;
emit WhiteListed(_member);
return true;
}
/**
* @dev removes a user from whitelist
* @param _member address to remove from whitelist
*/
function removeFromWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = false;
emit BlackListed(_member);
return true;
}
/**
* @dev change operator address
* @param _newOperator address of new operator
*/
function changeOperator(address _newOperator) public onlyOperator returns (bool) {
operator = _newOperator;
return true;
}
/**
* @dev burns an amount of the tokens of the message sender
* account.
* @param amount The amount that will be burnt.
*/
function burn(uint256 amount) public returns (bool) {
_burn(msg.sender, amount);
return true;
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public returns (bool) {
_burnFrom(from, value);
return true;
}
/**
* @dev function that mints an amount of the token and assigns it to
* an account.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function mint(address account, uint256 amount) public onlyOperator {
_mint(account, amount);
}
/**
* @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 canTransfer(to) returns (bool) {
require(isLockedForMV[msg.sender] < now); // if not voted under governance
require(value <= _balances[msg.sender]);
_transfer(to, value);
return true;
}
/**
* @dev Transfer tokens to the operator from the specified address
* @param from The address to transfer from.
* @param value The amount to be transferred.
*/
function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) {
require(value <= _balances[from]);
_transferFrom(from, operator, value);
return true;
}
/**
* @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
canTransfer(to)
returns (bool)
{
require(isLockedForMV[from] < now); // if not voted under governance
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
_transferFrom(from, to, value);
return true;
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyOperator {
if (_days.add(now) > isLockedForMV[_of])
isLockedForMV[_of] = _days.add(now);
}
/**
* @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) internal {
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
}
/**
* @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
)
internal
{
_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);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
import "../../interfaces/IPooledStaking.sol";
import "../claims/ClaimsData.sol";
import "./NXMToken.sol";
import "./external/LockHandler.sol";
contract TokenController is LockHandler, Iupgradable {
using SafeMath for uint256;
struct CoverInfo {
uint16 claimCount;
bool hasOpenClaim;
bool hasAcceptedClaim;
// note: still 224 bits available here, can be used later
}
NXMToken public token;
IPooledStaking public pooledStaking;
uint public minCALockTime;
uint public claimSubmissionGracePeriod;
// coverId => CoverInfo
mapping(uint => CoverInfo) public coverInfo;
event Locked(address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity);
event Unlocked(address indexed _of, bytes32 indexed _reason, uint256 _amount);
event Burned(address indexed member, bytes32 lockedUnder, uint256 amount);
modifier onlyGovernance {
require(msg.sender == ms.getLatestAddress("GV"), "TokenController: Caller is not governance");
_;
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {
token = NXMToken(ms.tokenAddress());
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
}
function markCoverClaimOpen(uint coverId) external onlyInternal {
CoverInfo storage info = coverInfo[coverId];
uint16 claimCount;
bool hasOpenClaim;
bool hasAcceptedClaim;
// reads all of them using a single SLOAD
(claimCount, hasOpenClaim, hasAcceptedClaim) = (info.claimCount, info.hasOpenClaim, info.hasAcceptedClaim);
// no safemath for uint16 but should be safe from
// overflows as there're max 2 claims per cover
claimCount = claimCount + 1;
require(claimCount <= 2, "TokenController: Max claim count exceeded");
require(hasOpenClaim == false, "TokenController: Cover already has an open claim");
require(hasAcceptedClaim == false, "TokenController: Cover already has accepted claims");
// should use a single SSTORE for both
(info.claimCount, info.hasOpenClaim) = (claimCount, true);
}
/**
* @param coverId cover id (careful, not claim id!)
* @param isAccepted claim verdict
*/
function markCoverClaimClosed(uint coverId, bool isAccepted) external onlyInternal {
CoverInfo storage info = coverInfo[coverId];
require(info.hasOpenClaim == true, "TokenController: Cover claim is not marked as open");
// should use a single SSTORE for both
(info.hasOpenClaim, info.hasAcceptedClaim) = (false, isAccepted);
}
/**
* @dev to change the operator address
* @param _newOperator is the new address of operator
*/
function changeOperator(address _newOperator) public onlyInternal {
token.changeOperator(_newOperator);
}
/**
* @dev Proxies token transfer through this contract to allow staking when members are locked for voting
* @param _from Source address
* @param _to Destination address
* @param _value Amount to transfer
*/
function operatorTransfer(address _from, address _to, uint _value) external onlyInternal returns (bool) {
require(msg.sender == address(pooledStaking), "TokenController: Call is only allowed from PooledStaking address");
token.operatorTransfer(_from, _value);
token.transfer(_to, _value);
return true;
}
/**
* @dev Locks a specified amount of tokens,
* for CLA reason and for a specified time
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function lockClaimAssessmentTokens(uint256 _amount, uint256 _time) external checkPause {
require(minCALockTime <= _time, "TokenController: Must lock for minimum time");
require(_time <= 180 days, "TokenController: Tokens can be locked for 180 days maximum");
// If tokens are already locked, then functions extendLock or
// increaseClaimAssessmentLock should be used to make any changes
_lock(msg.sender, "CLA", _amount, _time);
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
* @param _of address whose tokens are to be locked
*/
function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time)
public
onlyInternal
returns (bool)
{
// If tokens are already locked, then functions extendLock or
// increaseLockAmount should be used to make any changes
_lock(_of, _reason, _amount, _time);
return true;
}
/**
* @dev Mints and locks a specified amount of tokens against an address,
* for a CN reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function mintCoverNote(
address _of,
bytes32 _reason,
uint256 _amount,
uint256 _time
) external onlyInternal {
require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked");
require(_amount != 0, "TokenController: Amount shouldn't be zero");
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
token.mint(address(this), _amount);
uint256 lockedUntil = now.add(_time);
locked[_of][_reason] = LockToken(_amount, lockedUntil, false);
emit Locked(_of, _reason, _amount, lockedUntil);
}
/**
* @dev Extends lock for reason CLA for a specified time
* @param _time Lock extension time in seconds
*/
function extendClaimAssessmentLock(uint256 _time) external checkPause {
uint256 validity = getLockedTokensValidity(msg.sender, "CLA");
require(validity.add(_time).sub(block.timestamp) <= 180 days, "TokenController: Tokens can be locked for 180 days maximum");
_extendLock(msg.sender, "CLA", _time);
}
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLockOf(address _of, bytes32 _reason, uint256 _time)
public
onlyInternal
returns (bool)
{
_extendLock(_of, _reason, _time);
return true;
}
/**
* @dev Increase number of tokens locked for a CLA reason
* @param _amount Number of tokens to be increased
*/
function increaseClaimAssessmentLock(uint256 _amount) external checkPause
{
require(_tokensLocked(msg.sender, "CLA") > 0, "TokenController: No tokens locked");
token.operatorTransfer(msg.sender, _amount);
locked[msg.sender]["CLA"].amount = locked[msg.sender]["CLA"].amount.add(_amount);
emit Locked(msg.sender, "CLA", _amount, locked[msg.sender]["CLA"].validity);
}
/**
* @dev burns tokens of an address
* @param _of is the address to burn tokens of
* @param amount is the amount to burn
* @return the boolean status of the burning process
*/
function burnFrom(address _of, uint amount) public onlyInternal returns (bool) {
return token.burnFrom(_of, amount);
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal {
_burnLockedTokens(_of, _reason, _amount);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal {
_reduceLock(_of, _reason, _time);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount)
public
onlyInternal
{
_releaseLockedTokens(_of, _reason, _amount);
}
/**
* @dev Adds an address to whitelist maintained in the contract
* @param _member address to add to whitelist
*/
function addToWhitelist(address _member) public onlyInternal {
token.addToWhiteList(_member);
}
/**
* @dev Removes an address from the whitelist in the token
* @param _member address to remove
*/
function removeFromWhitelist(address _member) public onlyInternal {
token.removeFromWhiteList(_member);
}
/**
* @dev Mints new token for an address
* @param _member address to reward the minted tokens
* @param _amount number of tokens to mint
*/
function mint(address _member, uint _amount) public onlyInternal {
token.mint(_member, _amount);
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyInternal {
token.lockForMemberVote(_of, _days);
}
/**
* @dev Unlocks the withdrawable tokens against CLA of a specified address
* @param _of Address of user, claiming back withdrawable tokens against CLA
*/
function withdrawClaimAssessmentTokens(address _of) external checkPause {
uint256 withdrawableTokens = _tokensUnlockable(_of, "CLA");
if (withdrawableTokens > 0) {
locked[_of]["CLA"].claimed = true;
emit Unlocked(_of, "CLA", withdrawableTokens);
token.transfer(_of, withdrawableTokens);
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param value value to set
*/
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "MNCLT") {
minCALockTime = value;
return;
}
if (code == "GRACEPER") {
claimSubmissionGracePeriod = value;
return;
}
revert("TokenController: invalid param code");
}
function getLockReasons(address _of) external view returns (bytes32[] memory reasons) {
return lockReason[_of];
}
/**
* @dev Gets the validity of locked tokens of a specified address
* @param _of The address to query the validity
* @param reason reason for which tokens were locked
*/
function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) {
validity = locked[_of][reason].validity;
}
/**
* @dev Gets the unlockable tokens of a specified address
* @param _of The address to query the the unlockable token count of
*/
function getUnlockableTokens(address _of)
public
view
returns (uint256 unlockableTokens)
{
for (uint256 i = 0; i < lockReason[_of].length; i++) {
unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i]));
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLocked(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensLocked(_of, _reason);
}
/**
* @dev Returns tokens locked and validity for a specified address and reason
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLockedWithValidity(address _of, bytes32 _reason)
public
view
returns (uint256 amount, uint256 validity)
{
bool claimed = locked[_of][_reason].claimed;
amount = locked[_of][_reason].amount;
validity = locked[_of][_reason].validity;
if (claimed) {
amount = 0;
}
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function tokensUnlockable(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensUnlockable(_of, _reason);
}
function totalSupply() public view returns (uint256)
{
return token.totalSupply();
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
public
view
returns (uint256 amount)
{
return _tokensLockedAtTime(_of, _reason, _time);
}
/**
* @dev Returns the total amount of tokens held by an address:
* transferable + locked + staked for pooled staking - pending burns.
* Used by Claims and Governance in member voting to calculate the user's vote weight.
*
* @param _of The address to query the total balance of
* @param _of The address to query the total balance of
*/
function totalBalanceOf(address _of) public view returns (uint256 amount) {
amount = token.balanceOf(_of);
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
uint stakerReward = pooledStaking.stakerReward(_of);
uint stakerDeposit = pooledStaking.stakerDeposit(_of);
amount = amount.add(stakerDeposit).add(stakerReward);
}
/**
* @dev Returns the total amount of locked and staked tokens.
* Used by MemberRoles to check eligibility for withdraw / switch membership.
* Includes tokens locked for claim assessment, tokens staked for risk assessment, and locked cover notes
* Does not take into account pending burns.
* @param _of member whose locked tokens are to be calculate
*/
function totalLockedBalance(address _of) public view returns (uint256 amount) {
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
amount = amount.add(pooledStaking.stakerDeposit(_of));
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal {
require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked");
require(_amount != 0, "TokenController: Amount shouldn't be zero");
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
token.operatorTransfer(_of, _amount);
uint256 validUntil = now.add(_time);
locked[_of][_reason] = LockToken(_amount, validUntil, false);
emit Locked(_of, _reason, _amount, validUntil);
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function _tokensLocked(address _of, bytes32 _reason)
internal
view
returns (uint256 amount)
{
if (!locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
internal
view
returns (uint256 amount)
{
if (locked[_of][_reason].validity > _time) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Extends lock for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function _extendLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked");
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked");
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount)
{
if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal {
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount");
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
// lock reason removal is skipped here: needs to be done from offchain
token.burn(_amount);
emit Burned(_of, _reason, _amount);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal
{
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount");
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
// lock reason removal is skipped here: needs to be done from offchain
token.transfer(_of, _amount);
emit Unlocked(_of, _reason, _amount);
}
function withdrawCoverNote(
address _of,
uint[] calldata _coverIds,
uint[] calldata _indexes
) external onlyInternal {
uint reasonCount = lockReason[_of].length;
uint lastReasonIndex = reasonCount.sub(1, "TokenController: No locked cover notes found");
uint totalAmount = 0;
// The iteration is done from the last to first to prevent reason indexes from
// changing due to the way we delete the items (copy last to current and pop last).
// The provided indexes array must be ordered, otherwise reason index checks will fail.
for (uint i = _coverIds.length; i > 0; i--) {
bool hasOpenClaim = coverInfo[_coverIds[i - 1]].hasOpenClaim;
require(hasOpenClaim == false, "TokenController: Cannot withdraw for cover with an open claim");
// note: cover owner is implicitly checked using the reason hash
bytes32 _reason = keccak256(abi.encodePacked("CN", _of, _coverIds[i - 1]));
uint _reasonIndex = _indexes[i - 1];
require(lockReason[_of][_reasonIndex] == _reason, "TokenController: Bad reason index");
uint amount = locked[_of][_reason].amount;
totalAmount = totalAmount.add(amount);
delete locked[_of][_reason];
if (lastReasonIndex != _reasonIndex) {
lockReason[_of][_reasonIndex] = lockReason[_of][lastReasonIndex];
}
lockReason[_of].pop();
emit Unlocked(_of, _reason, amount);
if (lastReasonIndex > 0) {
lastReasonIndex = lastReasonIndex.sub(1, "TokenController: Reason count mismatch");
}
}
token.transfer(_of, totalAmount);
}
function removeEmptyReason(address _of, bytes32 _reason, uint _index) external {
_removeEmptyReason(_of, _reason, _index);
}
function removeMultipleEmptyReasons(
address[] calldata _members,
bytes32[] calldata _reasons,
uint[] calldata _indexes
) external {
require(_members.length == _reasons.length, "TokenController: members and reasons array lengths differ");
require(_reasons.length == _indexes.length, "TokenController: reasons and indexes array lengths differ");
for (uint i = _members.length; i > 0; i--) {
uint idx = i - 1;
_removeEmptyReason(_members[idx], _reasons[idx], _indexes[idx]);
}
}
function _removeEmptyReason(address _of, bytes32 _reason, uint _index) internal {
uint lastReasonIndex = lockReason[_of].length.sub(1, "TokenController: lockReason is empty");
require(lockReason[_of][_index] == _reason, "TokenController: bad reason index");
require(locked[_of][_reason].amount == 0, "TokenController: reason amount is not zero");
if (lastReasonIndex != _index) {
lockReason[_of][_index] = lockReason[_of][lastReasonIndex];
}
lockReason[_of].pop();
}
function initialize() external {
require(claimSubmissionGracePeriod == 0, "TokenController: Already initialized");
claimSubmissionGracePeriod = 120 days;
migrate();
}
function migrate() internal {
ClaimsData cd = ClaimsData(ms.getLatestAddress("CD"));
uint totalClaims = cd.actualClaimLength() - 1;
// fix stuck claims 21 & 22
cd.changeFinalVerdict(20, -1);
cd.setClaimStatus(20, 6);
cd.changeFinalVerdict(21, -1);
cd.setClaimStatus(21, 6);
// reduce claim assessment lock period for members locked for more than 180 days
// extracted using scripts/extract-ca-locked-more-than-180.js
address payable[3] memory members = [
0x4a9fA34da6d2378c8f3B9F6b83532B169beaEDFc,
0x6b5DCDA27b5c3d88e71867D6b10b35372208361F,
0x8B6D1e5b4db5B6f9aCcc659e2b9619B0Cd90D617
];
for (uint i = 0; i < members.length; i++) {
if (locked[members[i]]["CLA"].validity > now + 180 days) {
locked[members[i]]["CLA"].validity = now + 180 days;
}
}
for (uint i = 1; i <= totalClaims; i++) {
(/*id*/, uint status) = cd.getClaimStatusNumber(i);
(/*id*/, uint coverId) = cd.getClaimCoverId(i);
int8 verdict = cd.getFinalVerdict(i);
// SLOAD
CoverInfo memory info = coverInfo[coverId];
info.claimCount = info.claimCount + 1;
info.hasAcceptedClaim = (status == 14);
info.hasOpenClaim = (verdict == 0);
// SSTORE
coverInfo[coverId] = info;
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../abstract/MasterAware.sol";
import "../capital/Pool.sol";
import "../cover/QuotationData.sol";
import "../oracles/PriceFeedOracle.sol";
import "../token/NXMToken.sol";
import "../token/TokenData.sol";
import "./LegacyMCR.sol";
contract MCR is MasterAware {
using SafeMath for uint;
Pool public pool;
QuotationData public qd;
// sizeof(qd) + 96 = 160 + 96 = 256 (occupies entire slot)
uint96 _unused;
// the following values are expressed in basis points
uint24 public mcrFloorIncrementThreshold = 13000;
uint24 public maxMCRFloorIncrement = 100;
uint24 public maxMCRIncrement = 500;
uint24 public gearingFactor = 48000;
// min update between MCR updates in seconds
uint24 public minUpdateTime = 3600;
uint112 public mcrFloor;
uint112 public mcr;
uint112 public desiredMCR;
uint32 public lastUpdateTime;
LegacyMCR public previousMCR;
event MCRUpdated(
uint mcr,
uint desiredMCR,
uint mcrFloor,
uint mcrETHWithGear,
uint totalSumAssured
);
uint constant UINT24_MAX = ~uint24(0);
uint constant MAX_MCR_ADJUSTMENT = 100;
uint constant BASIS_PRECISION = 10000;
constructor (address masterAddress) public {
changeMasterAddress(masterAddress);
if (masterAddress != address(0)) {
previousMCR = LegacyMCR(master.getLatestAddress("MC"));
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
qd = QuotationData(master.getLatestAddress("QD"));
pool = Pool(master.getLatestAddress("P1"));
initialize();
}
function initialize() internal {
address currentMCR = master.getLatestAddress("MC");
if (address(previousMCR) == address(0) || currentMCR != address(this)) {
// already initialized or not ready for initialization
return;
}
// fetch MCR parameters from previous contract
uint112 minCap = 7000 * 1e18;
mcrFloor = uint112(previousMCR.variableMincap()) + minCap;
mcr = uint112(previousMCR.getLastMCREther());
desiredMCR = mcr;
mcrFloorIncrementThreshold = uint24(previousMCR.dynamicMincapThresholdx100());
maxMCRFloorIncrement = uint24(previousMCR.dynamicMincapIncrementx100());
// set last updated time to now
lastUpdateTime = uint32(block.timestamp);
previousMCR = LegacyMCR(address(0));
}
/**
* @dev Gets total sum assured (in ETH).
* @return amount of sum assured
*/
function getAllSumAssurance() public view returns (uint) {
PriceFeedOracle priceFeed = pool.priceFeedOracle();
address daiAddress = priceFeed.daiAddress();
uint ethAmount = qd.getTotalSumAssured("ETH").mul(1e18);
uint daiAmount = qd.getTotalSumAssured("DAI").mul(1e18);
uint daiRate = priceFeed.getAssetToEthRate(daiAddress);
uint daiAmountInEth = daiAmount.mul(daiRate).div(1e18);
return ethAmount.add(daiAmountInEth);
}
/*
* @dev trigger an MCR update. Current virtual MCR value is synced to storage, mcrFloor is potentially updated
* and a new desiredMCR value to move towards is set.
*
*/
function updateMCR() public {
_updateMCR(pool.getPoolValueInEth(), false);
}
function updateMCRInternal(uint poolValueInEth, bool forceUpdate) public onlyInternal {
_updateMCR(poolValueInEth, forceUpdate);
}
function _updateMCR(uint poolValueInEth, bool forceUpdate) internal {
// read with 1 SLOAD
uint _mcrFloorIncrementThreshold = mcrFloorIncrementThreshold;
uint _maxMCRFloorIncrement = maxMCRFloorIncrement;
uint _gearingFactor = gearingFactor;
uint _minUpdateTime = minUpdateTime;
uint _mcrFloor = mcrFloor;
// read with 1 SLOAD
uint112 _mcr = mcr;
uint112 _desiredMCR = desiredMCR;
uint32 _lastUpdateTime = lastUpdateTime;
if (!forceUpdate && _lastUpdateTime + _minUpdateTime > block.timestamp) {
return;
}
if (block.timestamp > _lastUpdateTime && pool.calculateMCRRatio(poolValueInEth, _mcr) >= _mcrFloorIncrementThreshold) {
// MCR floor updates by up to maxMCRFloorIncrement percentage per day whenever the MCR ratio exceeds 1.3
// MCR floor is monotonically increasing.
uint basisPointsAdjustment = min(
_maxMCRFloorIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days),
_maxMCRFloorIncrement
);
uint newMCRFloor = _mcrFloor.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION);
require(newMCRFloor <= uint112(~0), 'MCR: newMCRFloor overflow');
mcrFloor = uint112(newMCRFloor);
}
// sync the current virtual MCR value to storage
uint112 newMCR = uint112(getMCR());
if (newMCR != _mcr) {
mcr = newMCR;
}
// the desiredMCR cannot fall below the mcrFloor but may have a higher or lower target value based
// on the changes in the totalSumAssured in the system.
uint totalSumAssured = getAllSumAssurance();
uint gearedMCR = totalSumAssured.mul(BASIS_PRECISION).div(_gearingFactor);
uint112 newDesiredMCR = uint112(max(gearedMCR, mcrFloor));
if (newDesiredMCR != _desiredMCR) {
desiredMCR = newDesiredMCR;
}
lastUpdateTime = uint32(block.timestamp);
emit MCRUpdated(mcr, desiredMCR, mcrFloor, gearedMCR, totalSumAssured);
}
/**
* @dev Calculates the current virtual MCR value. The virtual MCR value moves towards the desiredMCR value away
* from the stored mcr value at constant velocity based on how much time passed from the lastUpdateTime.
* The total change in virtual MCR cannot exceed 1% of stored mcr.
*
* This approach allows for the MCR to change smoothly across time without sudden jumps between values, while
* always progressing towards the desiredMCR goal. The desiredMCR can change subject to the call of _updateMCR
* so the virtual MCR value may change direction and start decreasing instead of increasing or vice-versa.
*
* @return mcr
*/
function getMCR() public view returns (uint) {
// read with 1 SLOAD
uint _mcr = mcr;
uint _desiredMCR = desiredMCR;
uint _lastUpdateTime = lastUpdateTime;
if (block.timestamp == _lastUpdateTime) {
return _mcr;
}
uint _maxMCRIncrement = maxMCRIncrement;
uint basisPointsAdjustment = _maxMCRIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days);
basisPointsAdjustment = min(basisPointsAdjustment, MAX_MCR_ADJUSTMENT);
if (_desiredMCR > _mcr) {
return min(_mcr.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION), _desiredMCR);
}
// in case desiredMCR <= mcr
return max(_mcr.mul(BASIS_PRECISION - basisPointsAdjustment).div(BASIS_PRECISION), _desiredMCR);
}
function getGearedMCR() external view returns (uint) {
return getAllSumAssurance().mul(BASIS_PRECISION).div(gearingFactor);
}
function min(uint x, uint y) pure internal returns (uint) {
return x < y ? x : y;
}
function max(uint x, uint y) pure internal returns (uint) {
return x > y ? x : y;
}
/**
* @dev Updates Uint Parameters
* @param code parameter code
* @param val new value
*/
function updateUintParameters(bytes8 code, uint val) public {
require(master.checkIsAuthToGoverned(msg.sender));
if (code == "DMCT") {
require(val <= UINT24_MAX, "MCR: value too large");
mcrFloorIncrementThreshold = uint24(val);
} else if (code == "DMCI") {
require(val <= UINT24_MAX, "MCR: value too large");
maxMCRFloorIncrement = uint24(val);
} else if (code == "MMIC") {
require(val <= UINT24_MAX, "MCR: value too large");
maxMCRIncrement = uint24(val);
} else if (code == "GEAR") {
require(val <= UINT24_MAX, "MCR: value too large");
gearingFactor = uint24(val);
} else if (code == "MUTI") {
require(val <= UINT24_MAX, "MCR: value too large");
minUpdateTime = uint24(val);
} else {
revert("Invalid param code");
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract INXMMaster {
address public tokenAddress;
address public owner;
uint public pauseTime;
function delegateCallBack(bytes32 myid) external;
function masterInitialized() public view returns (bool);
function isInternal(address _add) public view returns (bool);
function isPause() public view returns (bool check);
function isOwner(address _add) public view returns (bool);
function isMember(address _add) public view returns (bool);
function checkIsAuthToGoverned(address _add) public view returns (bool);
function updatePauseTime(uint _time) public;
function dAppLocker() public view returns (address _add);
function dAppToken() public view returns (address _add);
function getLatestAddress(bytes2 _contractName) public view returns (address payable contractAddress);
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
//Claims Reward Contract contains the functions for calculating number of tokens
// that will get rewarded, unlocked or burned depending upon the status of claim.
pragma solidity ^0.5.0;
import "../../interfaces/IPooledStaking.sol";
import "../capital/Pool.sol";
import "../cover/QuotationData.sol";
import "../governance/Governance.sol";
import "../token/TokenData.sol";
import "../token/TokenFunctions.sol";
import "./Claims.sol";
import "./ClaimsData.sol";
import "../capital/MCR.sol";
contract ClaimsReward is Iupgradable {
using SafeMath for uint;
NXMToken internal tk;
TokenController internal tc;
TokenData internal td;
QuotationData internal qd;
Claims internal c1;
ClaimsData internal cd;
Pool internal pool;
Governance internal gv;
IPooledStaking internal pooledStaking;
MemberRoles internal memberRoles;
MCR public mcr;
// assigned in constructor
address public DAI;
// constants
address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint private constant DECIMAL1E18 = uint(10) ** 18;
constructor (address masterAddress, address _daiAddress) public {
changeMasterAddress(masterAddress);
DAI = _daiAddress;
}
function changeDependentContractAddress() public onlyInternal {
c1 = Claims(ms.getLatestAddress("CL"));
cd = ClaimsData(ms.getLatestAddress("CD"));
tk = NXMToken(ms.tokenAddress());
tc = TokenController(ms.getLatestAddress("TC"));
td = TokenData(ms.getLatestAddress("TD"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
memberRoles = MemberRoles(ms.getLatestAddress("MR"));
pool = Pool(ms.getLatestAddress("P1"));
mcr = MCR(ms.getLatestAddress("MC"));
}
/// @dev Decides the next course of action for a given claim.
function changeClaimStatus(uint claimid) public checkPause onlyInternal {
(, uint coverid) = cd.getClaimCoverId(claimid);
(, uint status) = cd.getClaimStatusNumber(claimid);
// when current status is "Pending-Claim Assessor Vote"
if (status == 0) {
_changeClaimStatusCA(claimid, coverid, status);
} else if (status >= 1 && status <= 5) {
_changeClaimStatusMV(claimid, coverid, status);
} else if (status == 12) {// when current status is "Claim Accepted Payout Pending"
bool payoutSucceeded = attemptClaimPayout(coverid);
if (payoutSucceeded) {
c1.setClaimStatus(claimid, 14);
} else {
c1.setClaimStatus(claimid, 12);
}
}
}
function getCurrencyAssetAddress(bytes4 currency) public view returns (address) {
if (currency == "ETH") {
return ETH;
}
if (currency == "DAI") {
return DAI;
}
revert("ClaimsReward: unknown asset");
}
function attemptClaimPayout(uint coverId) internal returns (bool success) {
uint sumAssured = qd.getCoverSumAssured(coverId);
// TODO: when adding new cover currencies, fetch the correct decimals for this multiplication
uint sumAssuredWei = sumAssured.mul(1e18);
// get asset address
bytes4 coverCurrency = qd.getCurrencyOfCover(coverId);
address asset = getCurrencyAssetAddress(coverCurrency);
// get payout address
address payable coverHolder = qd.getCoverMemberAddress(coverId);
address payable payoutAddress = memberRoles.getClaimPayoutAddress(coverHolder);
// execute the payout
bool payoutSucceeded = pool.sendClaimPayout(asset, payoutAddress, sumAssuredWei);
if (payoutSucceeded) {
// burn staked tokens
(, address scAddress) = qd.getscAddressOfCover(coverId);
uint tokenPrice = pool.getTokenPrice(asset);
// note: for new assets "18" needs to be replaced with target asset decimals
uint burnNXMAmount = sumAssuredWei.mul(1e18).div(tokenPrice);
pooledStaking.pushBurn(scAddress, burnNXMAmount);
// adjust total sum assured
(, address coverContract) = qd.getscAddressOfCover(coverId);
qd.subFromTotalSumAssured(coverCurrency, sumAssured);
qd.subFromTotalSumAssuredSC(coverContract, coverCurrency, sumAssured);
// update MCR since total sum assured and MCR% change
mcr.updateMCRInternal(pool.getPoolValueInEth(), true);
return true;
}
return false;
}
/// @dev Amount of tokens to be rewarded to a user for a particular vote id.
/// @param check 1 -> CA vote, else member vote
/// @param voteid vote id for which reward has to be Calculated
/// @param flag if 1 calculate even if claimed,else don't calculate if already claimed
/// @return tokenCalculated reward to be given for vote id
/// @return lastClaimedCheck true if final verdict is still pending for that voteid
/// @return tokens number of tokens locked under that voteid
/// @return perc percentage of reward to be given.
function getRewardToBeGiven(
uint check,
uint voteid,
uint flag
)
public
view
returns (
uint tokenCalculated,
bool lastClaimedCheck,
uint tokens,
uint perc
)
{
uint claimId;
int8 verdict;
bool claimed;
uint tokensToBeDist;
uint totalTokens;
(tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid);
lastClaimedCheck = false;
int8 claimVerdict = cd.getFinalVerdict(claimId);
if (claimVerdict == 0) {
lastClaimedCheck = true;
}
if (claimVerdict == verdict && (claimed == false || flag == 1)) {
if (check == 1) {
(perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId);
} else {
(, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId);
}
if (perc > 0) {
if (check == 1) {
if (verdict == 1) {
(, totalTokens,) = cd.getClaimsTokenCA(claimId);
} else {
(,, totalTokens) = cd.getClaimsTokenCA(claimId);
}
} else {
if (verdict == 1) {
(, totalTokens,) = cd.getClaimsTokenMV(claimId);
} else {
(,, totalTokens) = cd.getClaimsTokenMV(claimId);
}
}
tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100));
}
}
}
/// @dev Transfers all tokens held by contract to a new contract in case of upgrade.
function upgrade(address _newAdd) public onlyInternal {
uint amount = tk.balanceOf(address(this));
if (amount > 0) {
require(tk.transfer(_newAdd, amount));
}
}
/// @dev Total reward in token due for claim by a user.
/// @return total total number of tokens
function getRewardToBeDistributedByUser(address _add) public view returns (uint total) {
uint lengthVote = cd.getVoteAddressCALength(_add);
uint lastIndexCA;
uint lastIndexMV;
uint tokenForVoteId;
uint voteId;
(lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add);
for (uint i = lastIndexCA; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(_add, i);
(tokenForVoteId,,,) = getRewardToBeGiven(1, voteId, 0);
total = total.add(tokenForVoteId);
}
lengthVote = cd.getVoteAddressMemberLength(_add);
for (uint j = lastIndexMV; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(_add, j);
(tokenForVoteId,,,) = getRewardToBeGiven(0, voteId, 0);
total = total.add(tokenForVoteId);
}
return (total);
}
/// @dev Gets reward amount and claiming status for a given claim id.
/// @return reward amount of tokens to user.
/// @return claimed true if already claimed false if yet to be claimed.
function getRewardAndClaimedStatus(uint check, uint claimId) public view returns (uint reward, bool claimed) {
uint voteId;
uint claimid;
uint lengthVote;
if (check == 1) {
lengthVote = cd.getVoteAddressCALength(msg.sender);
for (uint i = 0; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(msg.sender, i);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) {break;}
}
} else {
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
for (uint j = 0; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(msg.sender, j);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) {break;}
}
}
(reward,,,) = getRewardToBeGiven(check, voteId, 1);
}
/**
* @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance
* Claim assesment, Risk assesment, Governance rewards
*/
function claimAllPendingReward(uint records) public isMemberAndcheckPause {
_claimRewardToBeDistributed(records);
pooledStaking.withdrawReward(msg.sender);
uint governanceRewards = gv.claimReward(msg.sender, records);
if (governanceRewards > 0) {
require(tk.transfer(msg.sender, governanceRewards));
}
}
/**
* @dev Function used to get pending rewards of a particular user address.
* @param _add user address.
* @return total reward amount of the user
*/
function getAllPendingRewardOfUser(address _add) public view returns (uint) {
uint caReward = getRewardToBeDistributedByUser(_add);
uint pooledStakingReward = pooledStaking.stakerReward(_add);
uint governanceReward = gv.getPendingReward(_add);
return caReward.add(pooledStakingReward).add(governanceReward);
}
/// @dev Rewards/Punishes users who participated in Claims assessment.
// Unlocking and burning of the tokens will also depend upon the status of claim.
/// @param claimid Claim Id.
function _rewardAgainstClaim(uint claimid, uint coverid, uint status) internal {
uint premiumNXM = qd.getCoverPremiumNXM(coverid);
uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100); // 20% of premium
uint percCA;
uint percMV;
(percCA, percMV) = cd.getRewardStatus(status);
cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens);
if (percCA > 0 || percMV > 0) {
tc.mint(address(this), distributableTokens);
}
// denied
if (status == 6 || status == 9 || status == 11) {
cd.changeFinalVerdict(claimid, -1);
tc.markCoverClaimClosed(coverid, false);
_burnCoverNoteDeposit(coverid);
// accepted
} else if (status == 7 || status == 8 || status == 10) {
cd.changeFinalVerdict(claimid, 1);
tc.markCoverClaimClosed(coverid, true);
_unlockCoverNote(coverid);
bool payoutSucceeded = attemptClaimPayout(coverid);
// 12 = payout pending, 14 = payout succeeded
uint nextStatus = payoutSucceeded ? 14 : 12;
c1.setClaimStatus(claimid, nextStatus);
}
}
function _burnCoverNoteDeposit(uint coverId) internal {
address _of = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
uint lockedAmount = tc.tokensLocked(_of, reason);
(uint amount,) = td.depositedCN(coverId);
amount = amount.div(2);
// limit burn amount to actual amount locked
uint burnAmount = lockedAmount < amount ? lockedAmount : amount;
if (burnAmount != 0) {
tc.burnLockedTokens(_of, reason, amount);
}
}
function _unlockCoverNote(uint coverId) internal {
address coverHolder = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId));
uint lockedCN = tc.tokensLocked(coverHolder, reason);
if (lockedCN != 0) {
tc.releaseLockedTokens(coverHolder, reason, lockedCN);
}
}
/// @dev Computes the result of Claim Assessors Voting for a given claim id.
function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency.
uint accept;
uint deny;
uint acceptAndDeny;
bool rewardOrPunish;
uint sumAssured;
(, accept) = cd.getClaimVote(claimid, 1);
(, deny) = cd.getClaimVote(claimid, - 1);
acceptAndDeny = accept.add(deny);
accept = accept.mul(100);
deny = deny.mul(100);
if (caTokens == 0) {
status = 3;
} else {
sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
// Min threshold reached tokens used for voting > 5* sum assured
if (caTokens > sumAssured.mul(5)) {
if (accept.div(acceptAndDeny) > 70) {
status = 7;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted));
rewardOrPunish = true;
} else if (deny.div(acceptAndDeny) > 70) {
status = 6;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied));
rewardOrPunish = true;
} else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 4;
} else {
status = 5;
}
} else {
if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 2;
} else {
status = 3;
}
}
}
c1.setClaimStatus(claimid, status);
if (rewardOrPunish) {
_rewardAgainstClaim(claimid, coverid, status);
}
}
}
/// @dev Computes the result of Member Voting for a given claim id.
function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint8 coverStatus;
uint statusOrig = status;
uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency.
// If tokens used for acceptance >50%, claim is accepted
uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
uint thresholdUnreached = 0;
// Minimum threshold for member voting is reached only when
// value of tokens used for voting > 5* sum assured of claim id
if (mvTokens < sumAssured.mul(5)) {
thresholdUnreached = 1;
}
uint accept;
(, accept) = cd.getClaimMVote(claimid, 1);
uint deny;
(, deny) = cd.getClaimMVote(claimid, - 1);
if (accept.add(deny) > 0) {
if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 8;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 9;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
}
if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) {
status = 10;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) {
status = 11;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
c1.setClaimStatus(claimid, status);
qd.changeCoverStatusNo(coverid, uint8(coverStatus));
// Reward/Punish Claim Assessors and Members who participated in Claims assessment
_rewardAgainstClaim(claimid, coverid, status);
}
}
/// @dev Allows a user to claim all pending Claims assessment rewards.
function _claimRewardToBeDistributed(uint _records) internal {
uint lengthVote = cd.getVoteAddressCALength(msg.sender);
uint voteid;
uint lastIndex;
(lastIndex,) = cd.getRewardDistributedIndex(msg.sender);
uint total = 0;
uint tokenForVoteId = 0;
bool lastClaimedCheck;
uint _days = td.lockCADays();
bool claimed;
uint counter = 0;
uint claimId;
uint perc;
uint i;
uint lastClaimed = lengthVote;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressCA(msg.sender, i);
(tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (perc > 0 && !claimed) {
counter++;
cd.setRewardClaimed(voteid, true);
} else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) {
(perc,,) = cd.getClaimRewardDetail(claimId);
if (perc == 0) {
counter++;
}
cd.setRewardClaimed(voteid, true);
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexCA(msg.sender, i);
}
else {
cd.setRewardDistributedIndexCA(msg.sender, lastClaimed);
}
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
lastClaimed = lengthVote;
_days = _days.mul(counter);
if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) {
tc.reduceLock(msg.sender, "CLA", _days);
}
(, lastIndex) = cd.getRewardDistributedIndex(msg.sender);
lastClaimed = lengthVote;
counter = 0;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressMember(msg.sender, i);
(tokenForVoteId, lastClaimedCheck,,) = getRewardToBeGiven(0, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (claimed == false && cd.getFinalVerdict(claimId) != 0) {
cd.setRewardClaimed(voteid, true);
counter++;
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (total > 0) {
require(tk.transfer(msg.sender, total));
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexMV(msg.sender, i);
}
else {
cd.setRewardDistributedIndexMV(msg.sender, lastClaimed);
}
}
/**
* @dev Function used to claim the commission earned by the staker.
*/
function _claimStakeCommission(uint _records, address _user) external onlyInternal {
uint total = 0;
uint len = td.getStakerStakedContractLength(_user);
uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user);
uint commissionEarned;
uint commissionRedeemed;
uint maxCommission;
uint lastCommisionRedeemed = len;
uint counter;
uint i;
for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) {
commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i);
commissionEarned = td.getStakerEarnedStakeCommission(_user, i);
maxCommission = td.getStakerInitialStakedAmountOnContract(
_user, i).mul(td.stakerMaxCommissionPer()).div(100);
if (lastCommisionRedeemed == len && maxCommission != commissionEarned)
lastCommisionRedeemed = i;
td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed));
total = total.add(commissionEarned.sub(commissionRedeemed));
counter++;
}
if (lastCommisionRedeemed == len) {
td.setLastCompletedStakeCommissionIndex(_user, i);
} else {
td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed);
}
if (total > 0)
require(tk.transfer(_user, total)); // solhint-disable-line
}
}
/* Copyright (C) 2021 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../abstract/MasterAware.sol";
import "../../interfaces/IPooledStaking.sol";
import "../capital/Pool.sol";
import "../claims/ClaimsData.sol";
import "../claims/ClaimsReward.sol";
import "../cover/QuotationData.sol";
import "../governance/MemberRoles.sol";
import "../token/TokenController.sol";
import "../capital/MCR.sol";
contract Incidents is MasterAware {
using SafeERC20 for IERC20;
using SafeMath for uint;
struct Incident {
address productId;
uint32 date;
uint priceBefore;
}
// contract identifiers
enum ID {CD, CR, QD, TC, MR, P1, PS, MC}
mapping(uint => address payable) public internalContracts;
Incident[] public incidents;
// product id => underlying token (ex. yDAI -> DAI)
mapping(address => address) public underlyingToken;
// product id => covered token (ex. 0xc7ed.....1 -> yDAI)
mapping(address => address) public coveredToken;
// claim id => payout amount
mapping(uint => uint) public claimPayout;
// product id => accumulated burn amount
mapping(address => uint) public accumulatedBurn;
// burn ratio in bps, ex 2000 for 20%
uint public BURN_RATIO;
// burn ratio in bps
uint public DEDUCTIBLE_RATIO;
uint constant BASIS_PRECISION = 10000;
event ProductAdded(
address indexed productId,
address indexed coveredToken,
address indexed underlyingToken
);
event IncidentAdded(
address indexed productId,
uint incidentDate,
uint priceBefore
);
modifier onlyAdvisoryBoard {
uint abRole = uint(MemberRoles.Role.AdvisoryBoard);
require(
memberRoles().checkRole(msg.sender, abRole),
"Incidents: Caller is not an advisory board member"
);
_;
}
function initialize() external {
require(BURN_RATIO == 0, "Already initialized");
BURN_RATIO = 2000;
DEDUCTIBLE_RATIO = 9000;
}
function addProducts(
address[] calldata _productIds,
address[] calldata _coveredTokens,
address[] calldata _underlyingTokens
) external onlyAdvisoryBoard {
require(
_productIds.length == _coveredTokens.length,
"Incidents: Protocols and covered tokens lengths differ"
);
require(
_productIds.length == _underlyingTokens.length,
"Incidents: Protocols and underyling tokens lengths differ"
);
for (uint i = 0; i < _productIds.length; i++) {
address id = _productIds[i];
require(coveredToken[id] == address(0), "Incidents: covered token is already set");
require(underlyingToken[id] == address(0), "Incidents: underlying token is already set");
coveredToken[id] = _coveredTokens[i];
underlyingToken[id] = _underlyingTokens[i];
emit ProductAdded(id, _coveredTokens[i], _underlyingTokens[i]);
}
}
function incidentCount() external view returns (uint) {
return incidents.length;
}
function addIncident(
address productId,
uint incidentDate,
uint priceBefore
) external onlyGovernance {
address underlying = underlyingToken[productId];
require(underlying != address(0), "Incidents: Unsupported product");
Incident memory incident = Incident(productId, uint32(incidentDate), priceBefore);
incidents.push(incident);
emit IncidentAdded(productId, incidentDate, priceBefore);
}
function redeemPayoutForMember(
uint coverId,
uint incidentId,
uint coveredTokenAmount,
address member
) external onlyInternal returns (uint claimId, uint payoutAmount, address payoutToken) {
(claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, member);
}
function redeemPayout(
uint coverId,
uint incidentId,
uint coveredTokenAmount
) external returns (uint claimId, uint payoutAmount, address payoutToken) {
(claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, msg.sender);
}
function _redeemPayout(
uint coverId,
uint incidentId,
uint coveredTokenAmount,
address coverOwner
) internal returns (uint claimId, uint payoutAmount, address coverAsset) {
QuotationData qd = quotationData();
Incident memory incident = incidents[incidentId];
uint sumAssured;
bytes4 currency;
{
address productId;
address _coverOwner;
(/* id */, _coverOwner, productId,
currency, sumAssured, /* premiumNXM */
) = qd.getCoverDetailsByCoverID1(coverId);
// check ownership and covered protocol
require(coverOwner == _coverOwner, "Incidents: Not cover owner");
require(productId == incident.productId, "Incidents: Bad incident id");
}
{
uint coverPeriod = uint(qd.getCoverPeriod(coverId)).mul(1 days);
uint coverExpirationDate = qd.getValidityOfCover(coverId);
uint coverStartDate = coverExpirationDate.sub(coverPeriod);
// check cover validity
require(coverStartDate <= incident.date, "Incidents: Cover start date is after the incident");
require(coverExpirationDate >= incident.date, "Incidents: Cover end date is before the incident");
// check grace period
uint gracePeriod = tokenController().claimSubmissionGracePeriod();
require(coverExpirationDate.add(gracePeriod) >= block.timestamp, "Incidents: Grace period has expired");
}
{
// assumes 18 decimals (eth & dai)
uint decimalPrecision = 1e18;
uint maxAmount;
// sumAssured is currently stored without decimals
uint coverAmount = sumAssured.mul(decimalPrecision);
{
// max amount check
uint deductiblePriceBefore = incident.priceBefore.mul(DEDUCTIBLE_RATIO).div(BASIS_PRECISION);
maxAmount = coverAmount.mul(decimalPrecision).div(deductiblePriceBefore);
require(coveredTokenAmount <= maxAmount, "Incidents: Amount exceeds sum assured");
}
// payoutAmount = coveredTokenAmount / maxAmount * coverAmount
// = coveredTokenAmount * coverAmount / maxAmount
payoutAmount = coveredTokenAmount.mul(coverAmount).div(maxAmount);
}
{
TokenController tc = tokenController();
// mark cover as having a successful claim
tc.markCoverClaimOpen(coverId);
tc.markCoverClaimClosed(coverId, true);
// create the claim
ClaimsData cd = claimsData();
claimId = cd.actualClaimLength();
cd.addClaim(claimId, coverId, coverOwner, now);
cd.callClaimEvent(coverId, coverOwner, claimId, now);
cd.setClaimStatus(claimId, 14);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimAccepted));
claimPayout[claimId] = payoutAmount;
}
coverAsset = claimsReward().getCurrencyAssetAddress(currency);
_sendPayoutAndPushBurn(
incident.productId,
address(uint160(coverOwner)),
coveredTokenAmount,
coverAsset,
payoutAmount
);
qd.subFromTotalSumAssured(currency, sumAssured);
qd.subFromTotalSumAssuredSC(incident.productId, currency, sumAssured);
mcr().updateMCRInternal(pool().getPoolValueInEth(), true);
}
function pushBurns(address productId, uint maxIterations) external {
uint burnAmount = accumulatedBurn[productId];
delete accumulatedBurn[productId];
require(burnAmount > 0, "Incidents: No burns to push");
require(maxIterations >= 30, "Incidents: Pass at least 30 iterations");
IPooledStaking ps = pooledStaking();
ps.pushBurn(productId, burnAmount);
ps.processPendingActions(maxIterations);
}
function withdrawAsset(address asset, address destination, uint amount) external onlyGovernance {
IERC20 token = IERC20(asset);
uint balance = token.balanceOf(address(this));
uint transferAmount = amount > balance ? balance : amount;
token.safeTransfer(destination, transferAmount);
}
function _sendPayoutAndPushBurn(
address productId,
address payable coverOwner,
uint coveredTokenAmount,
address coverAsset,
uint payoutAmount
) internal {
address _coveredToken = coveredToken[productId];
// pull depegged tokens
IERC20(_coveredToken).safeTransferFrom(msg.sender, address(this), coveredTokenAmount);
Pool p1 = pool();
// send the payoutAmount
{
address payable payoutAddress = memberRoles().getClaimPayoutAddress(coverOwner);
bool success = p1.sendClaimPayout(coverAsset, payoutAddress, payoutAmount);
require(success, "Incidents: Payout failed");
}
{
// burn
uint decimalPrecision = 1e18;
uint assetPerNxm = p1.getTokenPrice(coverAsset);
uint maxBurnAmount = payoutAmount.mul(decimalPrecision).div(assetPerNxm);
uint burnAmount = maxBurnAmount.mul(BURN_RATIO).div(BASIS_PRECISION);
accumulatedBurn[productId] = accumulatedBurn[productId].add(burnAmount);
}
}
function claimsData() internal view returns (ClaimsData) {
return ClaimsData(internalContracts[uint(ID.CD)]);
}
function claimsReward() internal view returns (ClaimsReward) {
return ClaimsReward(internalContracts[uint(ID.CR)]);
}
function quotationData() internal view returns (QuotationData) {
return QuotationData(internalContracts[uint(ID.QD)]);
}
function tokenController() internal view returns (TokenController) {
return TokenController(internalContracts[uint(ID.TC)]);
}
function memberRoles() internal view returns (MemberRoles) {
return MemberRoles(internalContracts[uint(ID.MR)]);
}
function pool() internal view returns (Pool) {
return Pool(internalContracts[uint(ID.P1)]);
}
function pooledStaking() internal view returns (IPooledStaking) {
return IPooledStaking(internalContracts[uint(ID.PS)]);
}
function mcr() internal view returns (MCR) {
return MCR(internalContracts[uint(ID.MC)]);
}
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "BURNRATE") {
require(value <= BASIS_PRECISION, "Incidents: Burn ratio cannot exceed 10000");
BURN_RATIO = value;
return;
}
if (code == "DEDUCTIB") {
require(value <= BASIS_PRECISION, "Incidents: Deductible ratio cannot exceed 10000");
DEDUCTIBLE_RATIO = value;
return;
}
revert("Incidents: Invalid parameter");
}
function changeDependentContractAddress() external {
INXMMaster master = INXMMaster(master);
internalContracts[uint(ID.CD)] = master.getLatestAddress("CD");
internalContracts[uint(ID.CR)] = master.getLatestAddress("CR");
internalContracts[uint(ID.QD)] = master.getLatestAddress("QD");
internalContracts[uint(ID.TC)] = master.getLatestAddress("TC");
internalContracts[uint(ID.MR)] = master.getLatestAddress("MR");
internalContracts[uint(ID.P1)] = master.getLatestAddress("P1");
internalContracts[uint(ID.PS)] = master.getLatestAddress("PS");
internalContracts[uint(ID.MC)] = master.getLatestAddress("MC");
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract TokenData is Iupgradable {
using SafeMath for uint;
address payable public walletAddress;
uint public lockTokenTimeAfterCoverExp;
uint public bookTime;
uint public lockCADays;
uint public lockMVDays;
uint public scValidDays;
uint public joiningFee;
uint public stakerCommissionPer;
uint public stakerMaxCommissionPer;
uint public tokenExponent;
uint public priceStep;
struct StakeCommission {
uint commissionEarned;
uint commissionRedeemed;
}
struct Stake {
address stakedContractAddress;
uint stakedContractIndex;
uint dateAdd;
uint stakeAmount;
uint unlockedAmount;
uint burnedAmount;
uint unLockableBeforeLastBurn;
}
struct Staker {
address stakerAddress;
uint stakerIndex;
}
struct CoverNote {
uint amount;
bool isDeposited;
}
/**
* @dev mapping of uw address to array of sc address to fetch
* all staked contract address of underwriter, pushing
* data into this array of Stake returns stakerIndex
*/
mapping(address => Stake[]) public stakerStakedContracts;
/**
* @dev mapping of sc address to array of UW address to fetch
* all underwritters of the staked smart contract
* pushing data into this mapped array returns scIndex
*/
mapping(address => Staker[]) public stakedContractStakers;
/**
* @dev mapping of staked contract Address to the array of StakeCommission
* here index of this array is stakedContractIndex
*/
mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission;
mapping(address => uint) public lastCompletedStakeCommission;
/**
* @dev mapping of the staked contract address to the current
* staker index who will receive commission.
*/
mapping(address => uint) public stakedContractCurrentCommissionIndex;
/**
* @dev mapping of the staked contract address to the
* current staker index to burn token from.
*/
mapping(address => uint) public stakedContractCurrentBurnIndex;
/**
* @dev mapping to return true if Cover Note deposited against coverId
*/
mapping(uint => CoverNote) public depositedCN;
mapping(address => uint) internal isBookedTokens;
event Commission(
address indexed stakedContractAddress,
address indexed stakerAddress,
uint indexed scIndex,
uint commissionAmount
);
constructor(address payable _walletAdd) public {
walletAddress = _walletAdd;
bookTime = 12 hours;
joiningFee = 2000000000000000; // 0.002 Ether
lockTokenTimeAfterCoverExp = 35 days;
scValidDays = 250;
lockCADays = 7 days;
lockMVDays = 2 days;
stakerCommissionPer = 20;
stakerMaxCommissionPer = 50;
tokenExponent = 4;
priceStep = 1000;
}
/**
* @dev Change the wallet address which receive Joining Fee
*/
function changeWalletAddress(address payable _address) external onlyInternal {
walletAddress = _address;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "TOKEXP") {
val = tokenExponent;
} else if (code == "TOKSTEP") {
val = priceStep;
} else if (code == "RALOCKT") {
val = scValidDays;
} else if (code == "RACOMM") {
val = stakerCommissionPer;
} else if (code == "RAMAXC") {
val = stakerMaxCommissionPer;
} else if (code == "CABOOKT") {
val = bookTime / (1 hours);
} else if (code == "CALOCKT") {
val = lockCADays / (1 days);
} else if (code == "MVLOCKT") {
val = lockMVDays / (1 days);
} else if (code == "QUOLOCKT") {
val = lockTokenTimeAfterCoverExp / (1 days);
} else if (code == "JOINFEE") {
val = joiningFee;
}
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {//solhint-disable-line
}
/**
* @dev to get the contract staked by a staker
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return the address of staked contract
*/
function getStakerStakedContractByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (address stakedContractAddress)
{
stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
}
/**
* @dev to get the staker's staked burned
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount burned
*/
function getStakerStakedBurnedByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint burnedAmount)
{
burnedAmount = stakerStakedContracts[
_stakerAddress][_stakerIndex].burnedAmount;
}
/**
* @dev to get the staker's staked unlockable before the last burn
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return unlockable staked tokens
*/
function getStakerStakedUnlockableBeforeLastBurnByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint unlockable)
{
unlockable = stakerStakedContracts[
_stakerAddress][_stakerIndex].unLockableBeforeLastBurn;
}
/**
* @dev to get the staker's staked contract index
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return is the index of the smart contract address
*/
function getStakerStakedContractIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint scIndex)
{
scIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
}
/**
* @dev to get the staker index of the staked contract
* @param _stakedContractAddress is the address of the staked contract
* @param _stakedContractIndex is the index of staked contract
* @return is the index of the staker
*/
function getStakedContractStakerIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (uint sIndex)
{
sIndex = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerIndex;
}
/**
* @dev to get the staker's initial staked amount on the contract
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return staked amount
*/
function getStakerInitialStakedAmountOnContract(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakeAmount;
}
/**
* @dev to get the staker's staked contract length
* @param _stakerAddress is the address of the staker
* @return length of staked contract
*/
function getStakerStakedContractLength(
address _stakerAddress
)
public
view
returns (uint length)
{
length = stakerStakedContracts[_stakerAddress].length;
}
/**
* @dev to get the staker's unlocked tokens which were staked
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount
*/
function getStakerUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].unlockedAmount;
}
/**
* @dev pushes the unlocked staked tokens by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount.add(_amount);
}
/**
* @dev pushes the Burned tokens for a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be burned.
*/
function pushBurnedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount.add(_amount);
}
/**
* @dev pushes the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function pushUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn.add(_amount);
}
/**
* @dev sets the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function setUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = _amount;
}
/**
* @dev pushes the earned commission earned by a staker.
* @param _stakerAddress address of staker.
* @param _stakedContractAddress address of smart contract.
* @param _stakedContractIndex index of the staker to distribute commission.
* @param _commissionAmount amount to be given as commission.
*/
function pushEarnedStakeCommissions(
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex,
uint _commissionAmount
)
public
onlyInternal
{
stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex].
commissionEarned = stakedContractStakeCommission[_stakedContractAddress][
_stakedContractIndex].commissionEarned.add(_commissionAmount);
emit Commission(
_stakerAddress,
_stakedContractAddress,
_stakedContractIndex,
_commissionAmount
);
}
/**
* @dev pushes the redeemed commission redeemed by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushRedeemedStakeCommissions(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
uint stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
address stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
stakedContractStakeCommission[stakedContractAddress][stakedContractIndex].
commissionRedeemed = stakedContractStakeCommission[
stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount);
}
/**
* @dev Gets stake commission given to an underwriter
* for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets stake commission redeemed by an underwriter
* for particular staked contract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
* @return commissionEarned total amount given to staker.
*/
function getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalEarnedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionEarned)
{
totalCommissionEarned = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionEarned = totalCommissionEarned.
add(_getStakerEarnedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalReedmedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionRedeemed)
{
totalCommissionRedeemed = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionRedeemed = totalCommissionRedeemed.add(
_getStakerRedeemedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev set flag to deposit/ undeposit cover note
* against a cover Id
* @param coverId coverId of Cover
* @param flag true/false for deposit/undeposit
*/
function setDepositCN(uint coverId, bool flag) public onlyInternal {
if (flag == true) {
require(!depositedCN[coverId].isDeposited, "Cover note already deposited");
}
depositedCN[coverId].isDeposited = flag;
}
/**
* @dev set locked cover note amount
* against a cover Id
* @param coverId coverId of Cover
* @param amount amount of nxm to be locked
*/
function setDepositCNAmount(uint coverId, uint amount) public onlyInternal {
depositedCN[coverId].amount = amount;
}
/**
* @dev to get the staker address on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @param _stakedContractIndex is the index of staked contract's index
* @return address of staker
*/
function getStakedContractStakerByIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (address stakerAddress)
{
stakerAddress = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerAddress;
}
/**
* @dev to get the length of stakers on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @return length in concern
*/
function getStakedContractStakersLength(
address _stakedContractAddress
)
public
view
returns (uint length)
{
length = stakedContractStakers[_stakedContractAddress].length;
}
/**
* @dev Adds a new stake record.
* @param _stakerAddress staker address.
* @param _stakedContractAddress smart contract address.
* @param _amount amountof NXM to be staked.
*/
function addStake(
address _stakerAddress,
address _stakedContractAddress,
uint _amount
)
public
onlyInternal
returns (uint scIndex)
{
scIndex = (stakedContractStakers[_stakedContractAddress].push(
Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1);
stakerStakedContracts[_stakerAddress].push(
Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0));
}
/**
* @dev books the user's tokens for maintaining Assessor Velocity,
* i.e. once a token is used to cast a vote as a Claims assessor,
* @param _of user's address.
*/
function bookCATokens(address _of) public onlyInternal {
require(!isCATokensBooked(_of), "Tokens already booked");
isBookedTokens[_of] = now.add(bookTime);
}
/**
* @dev to know if claim assessor's tokens are booked or not
* @param _of is the claim assessor's address in concern
* @return boolean representing the status of tokens booked
*/
function isCATokensBooked(address _of) public view returns (bool res) {
if (now < isBookedTokens[_of])
res = true;
}
/**
* @dev Sets the index which will receive commission.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentCommissionIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index;
}
/**
* @dev Sets the last complete commission index
* @param _stakerAddress smart contract address.
* @param _index current index.
*/
function setLastCompletedStakeCommissionIndex(
address _stakerAddress,
uint _index
)
public
onlyInternal
{
lastCompletedStakeCommission[_stakerAddress] = _index;
}
/**
* @dev Sets the index till which commission is distrubuted.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentBurnIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentBurnIndex[_stakedContractAddress] = _index;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "TOKEXP") {
_setTokenExponent(val);
} else if (code == "TOKSTEP") {
_setPriceStep(val);
} else if (code == "RALOCKT") {
_changeSCValidDays(val);
} else if (code == "RACOMM") {
_setStakerCommissionPer(val);
} else if (code == "RAMAXC") {
_setStakerMaxCommissionPer(val);
} else if (code == "CABOOKT") {
_changeBookTime(val * 1 hours);
} else if (code == "CALOCKT") {
_changelockCADays(val * 1 days);
} else if (code == "MVLOCKT") {
_changelockMVDays(val * 1 days);
} else if (code == "QUOLOCKT") {
_setLockTokenTimeAfterCoverExp(val * 1 days);
} else if (code == "JOINFEE") {
_setJoiningFee(val);
} else {
revert("Invalid param code");
}
}
/**
* @dev Internal function to get stake commission given to an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionEarned;
}
/**
* @dev Internal function to get stake commission redeemed by an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionRedeemed;
}
/**
* @dev to set the percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerCommissionPer(uint _val) internal {
stakerCommissionPer = _val;
}
/**
* @dev to set the max percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerMaxCommissionPer(uint _val) internal {
stakerMaxCommissionPer = _val;
}
/**
* @dev to set the token exponent value
* @param _val is new value
*/
function _setTokenExponent(uint _val) internal {
tokenExponent = _val;
}
/**
* @dev to set the price step
* @param _val is new value
*/
function _setPriceStep(uint _val) internal {
priceStep = _val;
}
/**
* @dev Changes number of days for which NXM needs to staked in case of underwriting
*/
function _changeSCValidDays(uint _days) internal {
scValidDays = _days;
}
/**
* @dev Changes the time period up to which tokens will be locked.
* Used to generate the validity period of tokens booked by
* a user for participating in claim's assessment/claim's voting.
*/
function _changeBookTime(uint _time) internal {
bookTime = _time;
}
/**
* @dev Changes lock CA days - number of days for which tokens
* are locked while submitting a vote.
*/
function _changelockCADays(uint _val) internal {
lockCADays = _val;
}
/**
* @dev Changes lock MV days - number of days for which tokens are locked
* while submitting a vote.
*/
function _changelockMVDays(uint _val) internal {
lockMVDays = _val;
}
/**
* @dev Changes extra lock period for a cover, post its expiry.
*/
function _setLockTokenTimeAfterCoverExp(uint time) internal {
lockTokenTimeAfterCoverExp = time;
}
/**
* @dev Set the joining fee for membership
*/
function _setJoiningFee(uint _amount) internal {
joiningFee = _amount;
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract QuotationData is Iupgradable {
using SafeMath for uint;
enum HCIDStatus {NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover}
enum CoverStatus {Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested}
struct Cover {
address payable memberAddress;
bytes4 currencyCode;
uint sumAssured;
uint16 coverPeriod;
uint validUntil;
address scAddress;
uint premiumNXM;
}
struct HoldCover {
uint holdCoverId;
address payable userAddress;
address scAddress;
bytes4 coverCurr;
uint[] coverDetails;
uint16 coverPeriod;
}
address public authQuoteEngine;
mapping(bytes4 => uint) internal currencyCSA;
mapping(address => uint[]) internal userCover;
mapping(address => uint[]) public userHoldedCover;
mapping(address => bool) public refundEligible;
mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd;
mapping(uint => uint8) public coverStatus;
mapping(uint => uint) public holdedCoverIDStatus;
mapping(uint => bool) public timestampRepeated;
Cover[] internal allCovers;
HoldCover[] internal allCoverHolded;
uint public stlp;
uint public stl;
uint public pm;
uint public minDays;
uint public tokensRetained;
address public kycAuthAddress;
event CoverDetailsEvent(
uint indexed cid,
address scAdd,
uint sumAssured,
uint expiry,
uint premium,
uint premiumNXM,
bytes4 curr
);
event CoverStatusEvent(uint indexed cid, uint8 statusNum);
constructor(address _authQuoteAdd, address _kycAuthAdd) public {
authQuoteEngine = _authQuoteAdd;
kycAuthAddress = _kycAuthAdd;
stlp = 90;
stl = 100;
pm = 30;
minDays = 30;
tokensRetained = 10;
allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0));
uint[] memory arr = new uint[](1);
allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0));
}
/// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be added.
function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount);
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount);
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].sub(_amount);
}
/// @dev Adds the amount in Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be added.
function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].add(_amount);
}
/// @dev sets bit for timestamp to avoid replay attacks.
function setTimestampRepeated(uint _timestamp) external onlyInternal {
timestampRepeated[_timestamp] = true;
}
/// @dev Creates a blank new cover.
function addCover(
uint16 _coverPeriod,
uint _sumAssured,
address payable _userAddress,
bytes4 _currencyCode,
address _scAddress,
uint premium,
uint premiumNXM
)
external
onlyInternal
{
uint expiryDate = now.add(uint(_coverPeriod).mul(1 days));
allCovers.push(Cover(_userAddress, _currencyCode,
_sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM));
uint cid = allCovers.length.sub(1);
userCover[_userAddress].push(cid);
emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode);
}
/// @dev create holded cover which will process after verdict of KYC.
function addHoldCover(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] calldata coverDetails,
uint16 coverPeriod
)
external
onlyInternal
{
uint holdedCoverLen = allCoverHolded.length;
holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending);
allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress,
coverCurr, coverDetails, coverPeriod));
userHoldedCover[from].push(allCoverHolded.length.sub(1));
}
///@dev sets refund eligible bit.
///@param _add user address.
///@param status indicates if user have pending kyc.
function setRefundEligible(address _add, bool status) external onlyInternal {
refundEligible[_add] = status;
}
/// @dev to set current status of particular holded coverID (1 for not completed KYC,
/// 2 for KYC passed, 3 for failed KYC or full refunded,
/// 4 for KYC completed but cover not processed)
function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal {
holdedCoverIDStatus[holdedCoverID] = status;
}
/**
* @dev to set address of kyc authentication
* @param _add is the new address
*/
function setKycAuthAddress(address _add) external onlyInternal {
kycAuthAddress = _add;
}
/// @dev Changes authorised address for generating quote off chain.
function changeAuthQuoteEngine(address _add) external onlyInternal {
authQuoteEngine = _add;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "STLP") {
val = stlp;
} else if (code == "STL") {
val = stl;
} else if (code == "PM") {
val = pm;
} else if (code == "QUOMIND") {
val = minDays;
} else if (code == "QUOTOK") {
val = tokensRetained;
}
}
/// @dev Gets Product details.
/// @return _minDays minimum cover period.
/// @return _PM Profit margin.
/// @return _STL short term Load.
/// @return _STLP short term load period.
function getProductDetails()
external
view
returns (
uint _minDays,
uint _pm,
uint _stl,
uint _stlp
)
{
_minDays = minDays;
_pm = pm;
_stl = stl;
_stlp = stlp;
}
/// @dev Gets total number covers created till date.
function getCoverLength() external view returns (uint len) {
return (allCovers.length);
}
/// @dev Gets Authorised Engine address.
function getAuthQuoteEngine() external view returns (address _add) {
_add = authQuoteEngine;
}
/// @dev Gets the Total Sum Assured amount of a given currency.
function getTotalSumAssured(bytes4 _curr) external view returns (uint amount) {
amount = currencyCSA[_curr];
}
/// @dev Gets all the Cover ids generated by a given address.
/// @param _add User's address.
/// @return allCover array of covers.
function getAllCoversOfUser(address _add) external view returns (uint[] memory allCover) {
return (userCover[_add]);
}
/// @dev Gets total number of covers generated by a given address
function getUserCoverLength(address _add) external view returns (uint len) {
len = userCover[_add].length;
}
/// @dev Gets the status of a given cover.
function getCoverStatusNo(uint _cid) external view returns (uint8) {
return coverStatus[_cid];
}
/// @dev Gets the Cover Period (in days) of a given cover.
function getCoverPeriod(uint _cid) external view returns (uint32 cp) {
cp = allCovers[_cid].coverPeriod;
}
/// @dev Gets the Sum Assured Amount of a given cover.
function getCoverSumAssured(uint _cid) external view returns (uint sa) {
sa = allCovers[_cid].sumAssured;
}
/// @dev Gets the Currency Name in which a given cover is assured.
function getCurrencyOfCover(uint _cid) external view returns (bytes4 curr) {
curr = allCovers[_cid].currencyCode;
}
/// @dev Gets the validity date (timestamp) of a given cover.
function getValidityOfCover(uint _cid) external view returns (uint date) {
date = allCovers[_cid].validUntil;
}
/// @dev Gets Smart contract address of cover.
function getscAddressOfCover(uint _cid) external view returns (uint, address) {
return (_cid, allCovers[_cid].scAddress);
}
/// @dev Gets the owner address of a given cover.
function getCoverMemberAddress(uint _cid) external view returns (address payable _add) {
_add = allCovers[_cid].memberAddress;
}
/// @dev Gets the premium amount of a given cover in NXM.
function getCoverPremiumNXM(uint _cid) external view returns (uint _premiumNXM) {
_premiumNXM = allCovers[_cid].premiumNXM;
}
/// @dev Provides the details of a cover Id
/// @param _cid cover Id
/// @return memberAddress cover user address.
/// @return scAddress smart contract Address
/// @return currencyCode currency of cover
/// @return sumAssured sum assured of cover
/// @return premiumNXM premium in NXM
function getCoverDetailsByCoverID1(
uint _cid
)
external
view
returns (
uint cid,
address _memberAddress,
address _scAddress,
bytes4 _currencyCode,
uint _sumAssured,
uint premiumNXM
)
{
return (
_cid,
allCovers[_cid].memberAddress,
allCovers[_cid].scAddress,
allCovers[_cid].currencyCode,
allCovers[_cid].sumAssured,
allCovers[_cid].premiumNXM
);
}
/// @dev Provides details of a cover Id
/// @param _cid cover Id
/// @return status status of cover.
/// @return sumAssured Sum assurance of cover.
/// @return coverPeriod Cover Period of cover (in days).
/// @return validUntil is validity of cover.
function getCoverDetailsByCoverID2(
uint _cid
)
external
view
returns (
uint cid,
uint8 status,
uint sumAssured,
uint16 coverPeriod,
uint validUntil
)
{
return (
_cid,
coverStatus[_cid],
allCovers[_cid].sumAssured,
allCovers[_cid].coverPeriod,
allCovers[_cid].validUntil
);
}
/// @dev Provides details of a holded cover Id
/// @param _hcid holded cover Id
/// @return scAddress SmartCover address of cover.
/// @return coverCurr currency of cover.
/// @return coverPeriod Cover Period of cover (in days).
function getHoldedCoverDetailsByID1(
uint _hcid
)
external
view
returns (
uint hcid,
address scAddress,
bytes4 coverCurr,
uint16 coverPeriod
)
{
return (
_hcid,
allCoverHolded[_hcid].scAddress,
allCoverHolded[_hcid].coverCurr,
allCoverHolded[_hcid].coverPeriod
);
}
/// @dev Gets total number holded covers created till date.
function getUserHoldedCoverLength(address _add) external view returns (uint) {
return userHoldedCover[_add].length;
}
/// @dev Gets holded cover index by index of user holded covers.
function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) {
return userHoldedCover[_add][index];
}
/// @dev Provides the details of a holded cover Id
/// @param _hcid holded cover Id
/// @return memberAddress holded cover user address.
/// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute.
function getHoldedCoverDetailsByID2(
uint _hcid
)
external
view
returns (
uint hcid,
address payable memberAddress,
uint[] memory coverDetails
)
{
return (
_hcid,
allCoverHolded[_hcid].userAddress,
allCoverHolded[_hcid].coverDetails
);
}
/// @dev Gets the Total Sum Assured amount of a given currency and smart contract address.
function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns (uint amount) {
amount = currencyCSAOfSCAdd[_add][_curr];
}
//solhint-disable-next-line
function changeDependentContractAddress() public {}
/// @dev Changes the status of a given cover.
/// @param _cid cover Id.
/// @param _stat New status.
function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal {
coverStatus[_cid] = _stat;
emit CoverStatusEvent(_cid, _stat);
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "STLP") {
_changeSTLP(val);
} else if (code == "STL") {
_changeSTL(val);
} else if (code == "PM") {
_changePM(val);
} else if (code == "QUOMIND") {
_changeMinDays(val);
} else if (code == "QUOTOK") {
_setTokensRetained(val);
} else {
revert("Invalid param code");
}
}
/// @dev Changes the existing Profit Margin value
function _changePM(uint _pm) internal {
pm = _pm;
}
/// @dev Changes the existing Short Term Load Period (STLP) value.
function _changeSTLP(uint _stlp) internal {
stlp = _stlp;
}
/// @dev Changes the existing Short Term Load (STL) value.
function _changeSTL(uint _stl) internal {
stl = _stl;
}
/// @dev Changes the existing Minimum cover period (in days)
function _changeMinDays(uint _days) internal {
minDays = _days;
}
/**
* @dev to set the the amount of tokens retained
* @param val is the amount retained
*/
function _setTokensRetained(uint val) internal {
tokensRetained = val;
}
}
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface OZIERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library OZSafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity ^0.5.0;
import "./INXMMaster.sol";
contract Iupgradable {
INXMMaster public ms;
address public nxMasterAddress;
modifier onlyInternal {
require(ms.isInternal(msg.sender));
_;
}
modifier isMemberAndcheckPause {
require(ms.isPause() == false && ms.isMember(msg.sender) == true);
_;
}
modifier onlyOwner {
require(ms.isOwner(msg.sender));
_;
}
modifier checkPause {
require(ms.isPause() == false);
_;
}
modifier isMember {
require(ms.isMember(msg.sender), "Not member");
_;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public;
/**
* @dev change master address
* @param _masterAddress is the new address
*/
function changeMasterAddress(address _masterAddress) public {
if (address(ms) != address(0)) {
require(address(ms) == msg.sender, "Not master");
}
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
}
pragma solidity ^0.5.0;
interface IPooledStaking {
function accumulateReward(address contractAddress, uint amount) external;
function pushBurn(address contractAddress, uint amount) external;
function hasPendingActions() external view returns (bool);
function processPendingActions(uint maxIterations) external returns (bool finished);
function contractStake(address contractAddress) external view returns (uint);
function stakerReward(address staker) external view returns (uint);
function stakerDeposit(address staker) external view returns (uint);
function stakerContractStake(address staker, address contractAddress) external view returns (uint);
function withdraw(uint amount) external;
function stakerMaxWithdrawable(address stakerAddress) external view returns (uint);
function withdrawReward(address stakerAddress) external;
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract ClaimsData is Iupgradable {
using SafeMath for uint;
struct Claim {
uint coverId;
uint dateUpd;
}
struct Vote {
address voter;
uint tokens;
uint claimId;
int8 verdict;
bool rewardClaimed;
}
struct ClaimsPause {
uint coverid;
uint dateUpd;
bool submit;
}
struct ClaimPauseVoting {
uint claimid;
uint pendingTime;
bool voting;
}
struct RewardDistributed {
uint lastCAvoteIndex;
uint lastMVvoteIndex;
}
struct ClaimRewardDetails {
uint percCA;
uint percMV;
uint tokenToBeDist;
}
struct ClaimTotalTokens {
uint accept;
uint deny;
}
struct ClaimRewardStatus {
uint percCA;
uint percMV;
}
ClaimRewardStatus[] internal rewardStatus;
Claim[] internal allClaims;
Vote[] internal allvotes;
ClaimsPause[] internal claimPause;
ClaimPauseVoting[] internal claimPauseVotingEP;
mapping(address => RewardDistributed) internal voterVoteRewardReceived;
mapping(uint => ClaimRewardDetails) internal claimRewardDetail;
mapping(uint => ClaimTotalTokens) internal claimTokensCA;
mapping(uint => ClaimTotalTokens) internal claimTokensMV;
mapping(uint => int8) internal claimVote;
mapping(uint => uint) internal claimsStatus;
mapping(uint => uint) internal claimState12Count;
mapping(uint => uint[]) internal claimVoteCA;
mapping(uint => uint[]) internal claimVoteMember;
mapping(address => uint[]) internal voteAddressCA;
mapping(address => uint[]) internal voteAddressMember;
mapping(address => uint[]) internal allClaimsByAddress;
mapping(address => mapping(uint => uint)) internal userClaimVoteCA;
mapping(address => mapping(uint => uint)) internal userClaimVoteMember;
mapping(address => uint) public userClaimVotePausedOn;
uint internal claimPauseLastsubmit;
uint internal claimStartVotingFirstIndex;
uint public pendingClaimStart;
uint public claimDepositTime;
uint public maxVotingTime;
uint public minVotingTime;
uint public payoutRetryTime;
uint public claimRewardPerc;
uint public minVoteThreshold;
uint public maxVoteThreshold;
uint public majorityConsensus;
uint public pauseDaysCA;
event ClaimRaise(
uint indexed coverId,
address indexed userAddress,
uint claimId,
uint dateSubmit
);
event VoteCast(
address indexed userAddress,
uint indexed claimId,
bytes4 indexed typeOf,
uint tokens,
uint submitDate,
int8 verdict
);
constructor() public {
pendingClaimStart = 1;
maxVotingTime = 48 * 1 hours;
minVotingTime = 12 * 1 hours;
payoutRetryTime = 24 * 1 hours;
allvotes.push(Vote(address(0), 0, 0, 0, false));
allClaims.push(Claim(0, 0));
claimDepositTime = 7 days;
claimRewardPerc = 20;
minVoteThreshold = 5;
maxVoteThreshold = 10;
majorityConsensus = 70;
pauseDaysCA = 3 days;
_addRewardIncentive();
}
/**
* @dev Updates the pending claim start variable,
* the lowest claim id with a pending decision/payout.
*/
function setpendingClaimStart(uint _start) external onlyInternal {
require(pendingClaimStart <= _start);
pendingClaimStart = _start;
}
/**
* @dev Updates the max vote index for which claim assessor has received reward
* @param _voter address of the voter.
* @param caIndex last index till which reward was distributed for CA
*/
function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex;
}
/**
* @dev Used to pause claim assessor activity for 3 days
* @param user Member address whose claim voting ability needs to be paused
*/
function setUserClaimVotePausedOn(address user) external {
require(ms.checkIsAuthToGoverned(msg.sender));
userClaimVotePausedOn[user] = now;
}
/**
* @dev Updates the max vote index for which member has received reward
* @param _voter address of the voter.
* @param mvIndex last index till which reward was distributed for member
*/
function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex;
}
/**
* @param claimid claim id.
* @param percCA reward Percentage reward for claim assessor
* @param percMV reward Percentage reward for members
* @param tokens total tokens to be rewarded
*/
function setClaimRewardDetail(
uint claimid,
uint percCA,
uint percMV,
uint tokens
)
external
onlyInternal
{
claimRewardDetail[claimid].percCA = percCA;
claimRewardDetail[claimid].percMV = percMV;
claimRewardDetail[claimid].tokenToBeDist = tokens;
}
/**
* @dev Sets the reward claim status against a vote id.
* @param _voteid vote Id.
* @param claimed true if reward for vote is claimed, else false.
*/
function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal {
allvotes[_voteid].rewardClaimed = claimed;
}
/**
* @dev Sets the final vote's result(either accepted or declined)of a claim.
* @param _claimId Claim Id.
* @param _verdict 1 if claim is accepted,-1 if declined.
*/
function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal {
claimVote[_claimId] = _verdict;
}
/**
* @dev Creates a new claim.
*/
function addClaim(
uint _claimId,
uint _coverId,
address _from,
uint _nowtime
)
external
onlyInternal
{
allClaims.push(Claim(_coverId, _nowtime));
allClaimsByAddress[_from].push(_claimId);
}
/**
* @dev Add Vote's details of a given claim.
*/
function addVote(
address _voter,
uint _tokens,
uint claimId,
int8 _verdict
)
external
onlyInternal
{
allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false));
}
/**
* @dev Stores the id of the claim assessor vote given to a claim.
* Maintains record of all votes given by all the CA to a claim.
* @param _claimId Claim Id to which vote has given by the CA.
* @param _voteid Vote Id.
*/
function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal {
claimVoteCA[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Claim assessor's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the CA.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteCA(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteCA[_from][_claimId] = _voteid;
voteAddressCA[_from].push(_voteid);
}
/**
* @dev Stores the tokens locked by the Claim Assessors during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens);
if (_vote == - 1)
claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens);
}
/**
* @dev Stores the tokens locked by the Members during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens);
if (_vote == - 1)
claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens);
}
/**
* @dev Stores the id of the member vote given to a claim.
* Maintains record of all votes given by all the Members to a claim.
* @param _claimId Claim Id to which vote has been given by the Member.
* @param _voteid Vote Id.
*/
function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal {
claimVoteMember[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Member's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the Member.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteMember(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteMember[_from][_claimId] = _voteid;
voteAddressMember[_from].push(_voteid);
}
/**
* @dev Increases the count of failure until payout of a claim is successful.
*/
function updateState12Count(uint _claimId, uint _cnt) external onlyInternal {
claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt);
}
/**
* @dev Sets status of a claim.
* @param _claimId Claim Id.
* @param _stat Status number.
*/
function setClaimStatus(uint _claimId, uint _stat) external onlyInternal {
claimsStatus[_claimId] = _stat;
}
/**
* @dev Sets the timestamp of a given claim at which the Claim's details has been updated.
* @param _claimId Claim Id of claim which has been changed.
* @param _dateUpd timestamp at which claim is updated.
*/
function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal {
allClaims[_claimId].dateUpd = _dateUpd;
}
/**
@dev Queues Claims during Emergency Pause.
*/
function setClaimAtEmergencyPause(
uint _coverId,
uint _dateUpd,
bool _submit
)
external
onlyInternal
{
claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit));
}
/**
* @dev Set submission flag for Claims queued during emergency pause.
* Set to true after EP is turned off and the claim is submitted .
*/
function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal {
claimPause[_index].submit = _submit;
}
/**
* @dev Sets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function setFirstClaimIndexToSubmitAfterEP(
uint _firstClaimIndexToSubmit
)
external
onlyInternal
{
claimPauseLastsubmit = _firstClaimIndexToSubmit;
}
/**
* @dev Sets the pending vote duration for a claim in case of emergency pause.
*/
function setPendingClaimDetails(
uint _claimId,
uint _pendingTime,
bool _voting
)
external
onlyInternal
{
claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting));
}
/**
* @dev Sets voting flag true after claim is reopened for voting after emergency pause.
*/
function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal {
claimPauseVotingEP[_claimId].voting = _vote;
}
/**
* @dev Sets the index from which claim needs to be
* reopened when emergency pause is swithched off.
*/
function setFirstClaimIndexToStartVotingAfterEP(
uint _claimStartVotingFirstIndex
)
external
onlyInternal
{
claimStartVotingFirstIndex = _claimStartVotingFirstIndex;
}
/**
* @dev Calls Vote Event.
*/
function callVoteEvent(
address _userAddress,
uint _claimId,
bytes4 _typeOf,
uint _tokens,
uint _submitDate,
int8 _verdict
)
external
onlyInternal
{
emit VoteCast(
_userAddress,
_claimId,
_typeOf,
_tokens,
_submitDate,
_verdict
);
}
/**
* @dev Calls Claim Event.
*/
function callClaimEvent(
uint _coverId,
address _userAddress,
uint _claimId,
uint _datesubmit
)
external
onlyInternal
{
emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit);
}
/**
* @dev Gets Uint Parameters by parameter code
* @param code whose details we want
* @return string value of the parameter
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "CAMAXVT") {
val = maxVotingTime / (1 hours);
} else if (code == "CAMINVT") {
val = minVotingTime / (1 hours);
} else if (code == "CAPRETRY") {
val = payoutRetryTime / (1 hours);
} else if (code == "CADEPT") {
val = claimDepositTime / (1 days);
} else if (code == "CAREWPER") {
val = claimRewardPerc;
} else if (code == "CAMINTH") {
val = minVoteThreshold;
} else if (code == "CAMAXTH") {
val = maxVoteThreshold;
} else if (code == "CACONPER") {
val = majorityConsensus;
} else if (code == "CAPAUSET") {
val = pauseDaysCA / (1 days);
}
}
/**
* @dev Get claim queued during emergency pause by index.
*/
function getClaimOfEmergencyPauseByIndex(
uint _index
)
external
view
returns (
uint coverId,
uint dateUpd,
bool submit
)
{
coverId = claimPause[_index].coverid;
dateUpd = claimPause[_index].dateUpd;
submit = claimPause[_index].submit;
}
/**
* @dev Gets the Claim's details of given claimid.
*/
function getAllClaimsByIndex(
uint _claimId
)
external
view
returns (
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return (
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the vote id of a given claim of a given Claim Assessor.
*/
function getUserClaimVoteCA(
address _add,
uint _claimId
)
external
view
returns (uint idVote)
{
return userClaimVoteCA[_add][_claimId];
}
/**
* @dev Gets the vote id of a given claim of a given member.
*/
function getUserClaimVoteMember(
address _add,
uint _claimId
)
external
view
returns (uint idVote)
{
return userClaimVoteMember[_add][_claimId];
}
/**
* @dev Gets the count of all votes.
*/
function getAllVoteLength() external view returns (uint voteCount) {
return allvotes.length.sub(1); // Start Index always from 1.
}
/**
* @dev Gets the status number of a given claim.
* @param _claimId Claim id.
* @return statno Status Number.
*/
function getClaimStatusNumber(uint _claimId) external view returns (uint claimId, uint statno) {
return (_claimId, claimsStatus[_claimId]);
}
/**
* @dev Gets the reward percentage to be distributed for a given status id
* @param statusNumber the number of type of status
* @return percCA reward Percentage for claim assessor
* @return percMV reward Percentage for members
*/
function getRewardStatus(uint statusNumber) external view returns (uint percCA, uint percMV) {
return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV);
}
/**
* @dev Gets the number of tries that have been made for a successful payout of a Claim.
*/
function getClaimState12Count(uint _claimId) external view returns (uint num) {
num = claimState12Count[_claimId];
}
/**
* @dev Gets the last update date of a claim.
*/
function getClaimDateUpd(uint _claimId) external view returns (uint dateupd) {
dateupd = allClaims[_claimId].dateUpd;
}
/**
* @dev Gets all Claims created by a user till date.
* @param _member user's address.
* @return claimarr List of Claims id.
*/
function getAllClaimsByAddress(address _member) external view returns (uint[] memory claimarr) {
return allClaimsByAddress[_member];
}
/**
* @dev Gets the number of tokens that has been locked
* while giving vote to a claim by Claim Assessors.
* @param _claimId Claim Id.
* @return accept Total number of tokens when CA accepts the claim.
* @return deny Total number of tokens when CA declines the claim.
*/
function getClaimsTokenCA(
uint _claimId
)
external
view
returns (
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensCA[_claimId].accept,
claimTokensCA[_claimId].deny
);
}
/**
* @dev Gets the number of tokens that have been
* locked while assessing a claim as a member.
* @param _claimId Claim Id.
* @return accept Total number of tokens in acceptance of the claim.
* @return deny Total number of tokens against the claim.
*/
function getClaimsTokenMV(
uint _claimId
)
external
view
returns (
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensMV[_claimId].accept,
claimTokensMV[_claimId].deny
);
}
/**
* @dev Gets the total number of votes cast as Claims assessor for/against a given claim
*/
function getCaClaimVotesToken(uint _claimId) external view returns (uint claimId, uint cnt) {
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets the total number of tokens cast as a member for/against a given claim
*/
function getMemberClaimVotesToken(
uint _claimId
)
external
view
returns (uint claimId, uint cnt)
{
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @dev Provides information of a vote when given its vote id.
* @param _voteid Vote Id.
*/
function getVoteDetails(uint _voteid)
external view
returns (
uint tokens,
uint claimId,
int8 verdict,
bool rewardClaimed
)
{
return (
allvotes[_voteid].tokens,
allvotes[_voteid].claimId,
allvotes[_voteid].verdict,
allvotes[_voteid].rewardClaimed
);
}
/**
* @dev Gets the voter's address of a given vote id.
*/
function getVoterVote(uint _voteid) external view returns (address voter) {
return allvotes[_voteid].voter;
}
/**
* @dev Provides information of a Claim when given its claim id.
* @param _claimId Claim Id.
*/
function getClaim(
uint _claimId
)
external
view
returns (
uint claimId,
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return (
_claimId,
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the total number of votes of a given claim.
* @param _claimId Claim Id.
* @param _ca if 1: votes given by Claim Assessors to a claim,
* else returns the number of votes of given by Members to a claim.
* @return len total number of votes for/against a given claim.
*/
function getClaimVoteLength(
uint _claimId,
uint8 _ca
)
external
view
returns (uint claimId, uint len)
{
claimId = _claimId;
if (_ca == 1)
len = claimVoteCA[_claimId].length;
else
len = claimVoteMember[_claimId].length;
}
/**
* @dev Gets the verdict of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return ver 1 if vote was given in favour,-1 if given in against.
*/
function getVoteVerdict(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (int8 ver)
{
if (_ca == 1)
ver = allvotes[claimVoteCA[_claimId][_index]].verdict;
else
ver = allvotes[claimVoteMember[_claimId][_index]].verdict;
}
/**
* @dev Gets the Number of tokens of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return tok Number of tokens.
*/
function getVoteToken(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (uint tok)
{
if (_ca == 1)
tok = allvotes[claimVoteCA[_claimId][_index]].tokens;
else
tok = allvotes[claimVoteMember[_claimId][_index]].tokens;
}
/**
* @dev Gets the Voter's address of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return voter Voter's address.
*/
function getVoteVoter(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (address voter)
{
if (_ca == 1)
voter = allvotes[claimVoteCA[_claimId][_index]].voter;
else
voter = allvotes[claimVoteMember[_claimId][_index]].voter;
}
/**
* @dev Gets total number of Claims created by a user till date.
* @param _add User's address.
*/
function getUserClaimCount(address _add) external view returns (uint len) {
len = allClaimsByAddress[_add].length;
}
/**
* @dev Calculates number of Claims that are in pending state.
*/
function getClaimLength() external view returns (uint len) {
len = allClaims.length.sub(pendingClaimStart);
}
/**
* @dev Gets the Number of all the Claims created till date.
*/
function actualClaimLength() external view returns (uint len) {
len = allClaims.length;
}
/**
* @dev Gets details of a claim.
* @param _index claim id = pending claim start + given index
* @param _add User's address.
* @return coverid cover against which claim has been submitted.
* @return claimId Claim Id.
* @return voteCA verdict of vote given as a Claim Assessor.
* @return voteMV verdict of vote given as a Member.
* @return statusnumber Status of claim.
*/
function getClaimFromNewStart(
uint _index,
address _add
)
external
view
returns (
uint coverid,
uint claimId,
int8 voteCA,
int8 voteMV,
uint statusnumber
)
{
uint i = pendingClaimStart.add(_index);
coverid = allClaims[i].coverId;
claimId = i;
if (userClaimVoteCA[_add][i] > 0)
voteCA = allvotes[userClaimVoteCA[_add][i]].verdict;
else
voteCA = 0;
if (userClaimVoteMember[_add][i] > 0)
voteMV = allvotes[userClaimVoteMember[_add][i]].verdict;
else
voteMV = 0;
statusnumber = claimsStatus[i];
}
/**
* @dev Gets details of a claim of a user at a given index.
*/
function getUserClaimByIndex(
uint _index,
address _add
)
external
view
returns (
uint status,
uint coverid,
uint claimId
)
{
claimId = allClaimsByAddress[_add][_index];
status = claimsStatus[claimId];
coverid = allClaims[claimId].coverId;
}
/**
* @dev Gets Id of all the votes given to a claim.
* @param _claimId Claim Id.
* @return ca id of all the votes given by Claim assessors to a claim.
* @return mv id of all the votes given by members to a claim.
*/
function getAllVotesForClaim(
uint _claimId
)
external
view
returns (
uint claimId,
uint[] memory ca,
uint[] memory mv
)
{
return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]);
}
/**
* @dev Gets Number of tokens deposit in a vote using
* Claim assessor's address and claim id.
* @return tokens Number of deposited tokens.
*/
function getTokensClaim(
address _of,
uint _claimId
)
external
view
returns (
uint claimId,
uint tokens
)
{
return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens);
}
/**
* @param _voter address of the voter.
* @return lastCAvoteIndex last index till which reward was distributed for CA
* @return lastMVvoteIndex last index till which reward was distributed for member
*/
function getRewardDistributedIndex(
address _voter
)
external
view
returns (
uint lastCAvoteIndex,
uint lastMVvoteIndex
)
{
return (
voterVoteRewardReceived[_voter].lastCAvoteIndex,
voterVoteRewardReceived[_voter].lastMVvoteIndex
);
}
/**
* @param claimid claim id.
* @return perc_CA reward Percentage for claim assessor
* @return perc_MV reward Percentage for members
* @return tokens total tokens to be rewarded
*/
function getClaimRewardDetail(
uint claimid
)
external
view
returns (
uint percCA,
uint percMV,
uint tokens
)
{
return (
claimRewardDetail[claimid].percCA,
claimRewardDetail[claimid].percMV,
claimRewardDetail[claimid].tokenToBeDist
);
}
/**
* @dev Gets cover id of a claim.
*/
function getClaimCoverId(uint _claimId) external view returns (uint claimId, uint coverid) {
return (_claimId, allClaims[_claimId].coverId);
}
/**
* @dev Gets total number of tokens staked during voting by Claim Assessors.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter).
*/
function getClaimVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets total number of tokens staked during voting by Members.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens,
* -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or
* deny on the basis of verdict given as parameter).
*/
function getClaimMVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @param _voter address of voteid
* @param index index to get voteid in CA
*/
function getVoteAddressCA(address _voter, uint index) external view returns (uint) {
return voteAddressCA[_voter][index];
}
/**
* @param _voter address of voter
* @param index index to get voteid in member vote
*/
function getVoteAddressMember(address _voter, uint index) external view returns (uint) {
return voteAddressMember[_voter][index];
}
/**
* @param _voter address of voter
*/
function getVoteAddressCALength(address _voter) external view returns (uint) {
return voteAddressCA[_voter].length;
}
/**
* @param _voter address of voter
*/
function getVoteAddressMemberLength(address _voter) external view returns (uint) {
return voteAddressMember[_voter].length;
}
/**
* @dev Gets the Final result of voting of a claim.
* @param _claimId Claim id.
* @return verdict 1 if claim is accepted, -1 if declined.
*/
function getFinalVerdict(uint _claimId) external view returns (int8 verdict) {
return claimVote[_claimId];
}
/**
* @dev Get number of Claims queued for submission during emergency pause.
*/
function getLengthOfClaimSubmittedAtEP() external view returns (uint len) {
len = claimPause.length;
}
/**
* @dev Gets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function getFirstClaimIndexToSubmitAfterEP() external view returns (uint indexToSubmit) {
indexToSubmit = claimPauseLastsubmit;
}
/**
* @dev Gets number of Claims to be reopened for voting post emergency pause period.
*/
function getLengthOfClaimVotingPause() external view returns (uint len) {
len = claimPauseVotingEP.length;
}
/**
* @dev Gets claim details to be reopened for voting after emergency pause.
*/
function getPendingClaimDetailsByIndex(
uint _index
)
external
view
returns (
uint claimId,
uint pendingTime,
bool voting
)
{
claimId = claimPauseVotingEP[_index].claimid;
pendingTime = claimPauseVotingEP[_index].pendingTime;
voting = claimPauseVotingEP[_index].voting;
}
/**
* @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off.
*/
function getFirstClaimIndexToStartVotingAfterEP() external view returns (uint firstindex) {
firstindex = claimStartVotingFirstIndex;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "CAMAXVT") {
_setMaxVotingTime(val * 1 hours);
} else if (code == "CAMINVT") {
_setMinVotingTime(val * 1 hours);
} else if (code == "CAPRETRY") {
_setPayoutRetryTime(val * 1 hours);
} else if (code == "CADEPT") {
_setClaimDepositTime(val * 1 days);
} else if (code == "CAREWPER") {
_setClaimRewardPerc(val);
} else if (code == "CAMINTH") {
_setMinVoteThreshold(val);
} else if (code == "CAMAXTH") {
_setMaxVoteThreshold(val);
} else if (code == "CACONPER") {
_setMajorityConsensus(val);
} else if (code == "CAPAUSET") {
_setPauseDaysCA(val * 1 days);
} else {
revert("Invalid param code");
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {}
/**
* @dev Adds status under which a claim can lie.
* @param percCA reward percentage for claim assessor
* @param percMV reward percentage for members
*/
function _pushStatus(uint percCA, uint percMV) internal {
rewardStatus.push(ClaimRewardStatus(percCA, percMV));
}
/**
* @dev adds reward incentive for all possible claim status for Claim assessors and members
*/
function _addRewardIncentive() internal {
_pushStatus(0, 0); // 0 Pending-Claim Assessor Vote
_pushStatus(0, 0); // 1 Pending-Claim Assessor Vote Denied, Pending Member Vote
_pushStatus(0, 0); // 2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote
_pushStatus(0, 0); // 3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote
_pushStatus(0, 0); // 4 Pending-CA Consensus not reached Accept, Pending Member Vote
_pushStatus(0, 0); // 5 Pending-CA Consensus not reached Deny, Pending Member Vote
_pushStatus(100, 0); // 6 Final-Claim Assessor Vote Denied
_pushStatus(100, 0); // 7 Final-Claim Assessor Vote Accepted
_pushStatus(0, 100); // 8 Final-Claim Assessor Vote Denied, MV Accepted
_pushStatus(0, 100); // 9 Final-Claim Assessor Vote Denied, MV Denied
_pushStatus(0, 0); // 10 Final-Claim Assessor Vote Accept, MV Nodecision
_pushStatus(0, 0); // 11 Final-Claim Assessor Vote Denied, MV Nodecision
_pushStatus(0, 0); // 12 Claim Accepted Payout Pending
_pushStatus(0, 0); // 13 Claim Accepted No Payout
_pushStatus(0, 0); // 14 Claim Accepted Payout Done
}
/**
* @dev Sets Maximum time(in seconds) for which claim assessment voting is open
*/
function _setMaxVotingTime(uint _time) internal {
maxVotingTime = _time;
}
/**
* @dev Sets Minimum time(in seconds) for which claim assessment voting is open
*/
function _setMinVotingTime(uint _time) internal {
minVotingTime = _time;
}
/**
* @dev Sets Minimum vote threshold required
*/
function _setMinVoteThreshold(uint val) internal {
minVoteThreshold = val;
}
/**
* @dev Sets Maximum vote threshold required
*/
function _setMaxVoteThreshold(uint val) internal {
maxVoteThreshold = val;
}
/**
* @dev Sets the value considered as Majority Consenus in voting
*/
function _setMajorityConsensus(uint val) internal {
majorityConsensus = val;
}
/**
* @dev Sets the payout retry time
*/
function _setPayoutRetryTime(uint _time) internal {
payoutRetryTime = _time;
}
/**
* @dev Sets percentage of reward given for claim assessment
*/
function _setClaimRewardPerc(uint _val) internal {
claimRewardPerc = _val;
}
/**
* @dev Sets the time for which claim is deposited.
*/
function _setClaimDepositTime(uint _time) internal {
claimDepositTime = _time;
}
/**
* @dev Sets number of days claim assessment will be paused
*/
function _setPauseDaysCA(uint val) internal {
pauseDaysCA = val;
}
}
pragma solidity ^0.5.0;
/**
* @title ERC1132 interface
* @dev see https://github.com/ethereum/EIPs/issues/1132
*/
contract LockHandler {
/**
* @dev Reasons why a user's tokens have been locked
*/
mapping(address => bytes32[]) public lockReason;
/**
* @dev locked token structure
*/
struct LockToken {
uint256 amount;
uint256 validity;
bool claimed;
}
/**
* @dev Holds number & validity of tokens locked for a given reason for
* a specified address
*/
mapping(address => mapping(bytes32 => LockToken)) public locked;
}
pragma solidity ^0.5.0;
interface LegacyMCR {
function addMCRData(uint mcrP, uint mcrE, uint vF, bytes4[] calldata curr, uint[] calldata _threeDayAvg, uint64 onlyDate) external;
function addLastMCRData(uint64 date) external;
function changeDependentContractAddress() external;
function getAllSumAssurance() external view returns (uint amount);
function _calVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp);
function calculateStepTokenPrice(bytes4 curr, uint mcrtp) external view returns (uint tokenPrice);
function calculateTokenPrice(bytes4 curr) external view returns (uint tokenPrice);
function calVtpAndMCRtp() external view returns (uint vtp, uint mcrtp);
function calculateVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp);
function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) external view returns (uint lowerThreshold, uint upperThreshold);
function getMaxSellTokens() external view returns (uint maxTokens);
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val);
function updateUintParameters(bytes8 code, uint val) external;
function variableMincap() external view returns (uint);
function dynamicMincapThresholdx100() external view returns (uint);
function dynamicMincapIncrementx100() external view returns (uint);
function getLastMCREther() external view returns (uint);
}
// /* Copyright (C) 2017 GovBlocks.io
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../token/TokenController.sol";
import "./MemberRoles.sol";
import "./ProposalCategory.sol";
import "./external/IGovernance.sol";
contract Governance is IGovernance, Iupgradable {
using SafeMath for uint;
enum ProposalStatus {
Draft,
AwaitingSolution,
VotingStarted,
Accepted,
Rejected,
Majority_Not_Reached_But_Accepted,
Denied
}
struct ProposalData {
uint propStatus;
uint finalVerdict;
uint category;
uint commonIncentive;
uint dateUpd;
address owner;
}
struct ProposalVote {
address voter;
uint proposalId;
uint dateAdd;
}
struct VoteTally {
mapping(uint => uint) memberVoteValue;
mapping(uint => uint) abVoteValue;
uint voters;
}
struct DelegateVote {
address follower;
address leader;
uint lastUpd;
}
ProposalVote[] internal allVotes;
DelegateVote[] public allDelegation;
mapping(uint => ProposalData) internal allProposalData;
mapping(uint => bytes[]) internal allProposalSolutions;
mapping(address => uint[]) internal allVotesByMember;
mapping(uint => mapping(address => bool)) public rewardClaimed;
mapping(address => mapping(uint => uint)) public memberProposalVote;
mapping(address => uint) public followerDelegation;
mapping(address => uint) internal followerCount;
mapping(address => uint[]) internal leaderDelegation;
mapping(uint => VoteTally) public proposalVoteTally;
mapping(address => bool) public isOpenForDelegation;
mapping(address => uint) public lastRewardClaimed;
bool internal constructorCheck;
uint public tokenHoldingTime;
uint internal roleIdAllowedToCatgorize;
uint internal maxVoteWeigthPer;
uint internal specialResolutionMajPerc;
uint internal maxFollowers;
uint internal totalProposals;
uint internal maxDraftTime;
MemberRoles internal memberRole;
ProposalCategory internal proposalCategory;
TokenController internal tokenInstance;
mapping(uint => uint) public proposalActionStatus;
mapping(uint => uint) internal proposalExecutionTime;
mapping(uint => mapping(address => bool)) public proposalRejectedByAB;
mapping(uint => uint) internal actionRejectedCount;
bool internal actionParamsInitialised;
uint internal actionWaitingTime;
uint constant internal AB_MAJ_TO_REJECT_ACTION = 3;
enum ActionStatus {
Pending,
Accepted,
Rejected,
Executed,
NoAction
}
/**
* @dev Called whenever an action execution is failed.
*/
event ActionFailed (
uint256 proposalId
);
/**
* @dev Called whenever an AB member rejects the action execution.
*/
event ActionRejected (
uint256 indexed proposalId,
address rejectedBy
);
/**
* @dev Checks if msg.sender is proposal owner
*/
modifier onlyProposalOwner(uint _proposalId) {
require(msg.sender == allProposalData[_proposalId].owner, "Not allowed");
_;
}
/**
* @dev Checks if proposal is opened for voting
*/
modifier voteNotStarted(uint _proposalId) {
require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted));
_;
}
/**
* @dev Checks if msg.sender is allowed to create proposal under given category
*/
modifier isAllowed(uint _categoryId) {
require(allowedToCreateProposal(_categoryId), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender is allowed categorize proposal under given category
*/
modifier isAllowedToCategorize() {
require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender had any pending rewards to be claimed
*/
modifier checkPendingRewards {
require(getPendingReward(msg.sender) == 0, "Claim reward");
_;
}
/**
* @dev Event emitted whenever a proposal is categorized
*/
event ProposalCategorized(
uint indexed proposalId,
address indexed categorizedBy,
uint categoryId
);
/**
* @dev Removes delegation of an address.
* @param _add address to undelegate.
*/
function removeDelegation(address _add) external onlyInternal {
_unDelegate(_add);
}
/**
* @dev Creates a new proposal
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
*/
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external isAllowed(_categoryId)
{
require(ms.isMember(msg.sender), "Not Member");
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
}
/**
* @dev Edits the details of an existing proposal
* @param _proposalId Proposal id that details needs to be updated
* @param _proposalDescHash Proposal description hash having long and short description of proposal.
*/
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external onlyProposalOwner(_proposalId)
{
require(
allProposalSolutions[_proposalId].length < 2,
"Not allowed"
);
allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft);
allProposalData[_proposalId].category = 0;
allProposalData[_proposalId].commonIncentive = 0;
emit Proposal(
allProposalData[_proposalId].owner,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
}
/**
* @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
*/
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
external
voteNotStarted(_proposalId) isAllowedToCategorize
{
_categorizeProposal(_proposalId, _categoryId, _incentive);
}
/**
* @dev Submit proposal with solution
* @param _proposalId Proposal id
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external
onlyProposalOwner(_proposalId)
{
require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution));
_proposalSubmission(_proposalId, _solutionHash, _action);
}
/**
* @dev Creates a new proposal with solution
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external isAllowed(_categoryId)
{
uint proposalId = totalProposals;
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
require(_categoryId > 0);
_proposalSubmission(
proposalId,
_solutionHash,
_action
);
}
/**
* @dev Submit a vote on the proposal.
* @param _proposalId to vote upon.
* @param _solutionChosen is the chosen vote.
*/
function submitVote(uint _proposalId, uint _solutionChosen) external {
require(allProposalData[_proposalId].propStatus ==
uint(Governance.ProposalStatus.VotingStarted), "Not allowed");
require(_solutionChosen < allProposalSolutions[_proposalId].length);
_submitVote(_proposalId, _solutionChosen);
}
/**
* @dev Closes the proposal.
* @param _proposalId of proposal to be closed.
*/
function closeProposal(uint _proposalId) external {
uint category = allProposalData[_proposalId].category;
uint _memberRole;
if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now &&
allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
} else {
require(canCloseProposal(_proposalId) == 1);
(, _memberRole,,,,,) = proposalCategory.category(allProposalData[_proposalId].category);
if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) {
_closeAdvisoryBoardVote(_proposalId, category);
} else {
_closeMemberVote(_proposalId, category);
}
}
}
/**
* @dev Claims reward for member.
* @param _memberAddress to claim reward of.
* @param _maxRecords maximum number of records to claim reward for.
_proposals list of proposals of which reward will be claimed.
* @return amount of pending reward.
*/
function claimReward(address _memberAddress, uint _maxRecords)
external returns (uint pendingDAppReward)
{
uint voteId;
address leader;
uint lastUpd;
require(msg.sender == ms.getLatestAddress("CR"));
uint delegationId = followerDelegation[_memberAddress];
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
uint totalVotes = allVotesByMember[leader].length;
uint lastClaimed = totalVotes;
uint j;
uint i;
for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) {
voteId = allVotesByMember[leader][i];
proposalId = allVotes[voteId].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) {
if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) {
if (!rewardClaimed[voteId][_memberAddress]) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
rewardClaimed[voteId][_memberAddress] = true;
j++;
}
} else {
if (lastClaimed == totalVotes) {
lastClaimed = i;
}
}
}
}
if (lastClaimed == totalVotes) {
lastRewardClaimed[_memberAddress] = i;
} else {
lastRewardClaimed[_memberAddress] = lastClaimed;
}
if (j > 0) {
emit RewardClaimed(
_memberAddress,
pendingDAppReward
);
}
}
/**
* @dev Sets delegation acceptance status of individual user
* @param _status delegation acceptance status
*/
function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards {
isOpenForDelegation[msg.sender] = _status;
}
/**
* @dev Delegates vote to an address.
* @param _add is the address to delegate vote to.
*/
function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards {
require(ms.masterInitialized());
require(allDelegation[followerDelegation[_add]].leader == address(0));
if (followerDelegation[msg.sender] > 0) {
require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now);
}
require(!alreadyDelegated(msg.sender));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner)));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)));
require(followerCount[_add] < maxFollowers);
if (allVotesByMember[msg.sender].length > 0) {
require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime)
< now);
}
require(ms.isMember(_add));
require(isOpenForDelegation[_add]);
allDelegation.push(DelegateVote(msg.sender, _add, now));
followerDelegation[msg.sender] = allDelegation.length - 1;
leaderDelegation[_add].push(allDelegation.length - 1);
followerCount[_add]++;
lastRewardClaimed[msg.sender] = allVotesByMember[_add].length;
}
/**
* @dev Undelegates the sender
*/
function unDelegate() external isMemberAndcheckPause checkPendingRewards {
_unDelegate(msg.sender);
}
/**
* @dev Triggers action of accepted proposal after waiting time is finished
*/
function triggerAction(uint _proposalId) external {
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger");
_triggerAction(_proposalId, allProposalData[_proposalId].category);
}
/**
* @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious
*/
function rejectAction(uint _proposalId) external {
require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now);
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted));
require(!proposalRejectedByAB[_proposalId][msg.sender]);
require(
keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category))
!= keccak256(abi.encodeWithSignature("swapABMember(address,address)"))
);
proposalRejectedByAB[_proposalId][msg.sender] = true;
actionRejectedCount[_proposalId]++;
emit ActionRejected(_proposalId, msg.sender);
if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) {
proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected);
}
}
/**
* @dev Sets intial actionWaitingTime value
* To be called after governance implementation has been updated
*/
function setInitialActionParameters() external onlyOwner {
require(!actionParamsInitialised);
actionParamsInitialised = true;
actionWaitingTime = 24 * 1 hours;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "GOVHOLD") {
val = tokenHoldingTime / (1 days);
} else if (code == "MAXFOL") {
val = maxFollowers;
} else if (code == "MAXDRFT") {
val = maxDraftTime / (1 days);
} else if (code == "EPTIME") {
val = ms.pauseTime() / (1 days);
} else if (code == "ACWT") {
val = actionWaitingTime / (1 hours);
}
}
/**
* @dev Gets all details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return category
* @return status
* @return finalVerdict
* @return totalReward
*/
function proposal(uint _proposalId)
external
view
returns (
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalRewar
)
{
return (
_proposalId,
allProposalData[_proposalId].category,
allProposalData[_proposalId].propStatus,
allProposalData[_proposalId].finalVerdict,
allProposalData[_proposalId].commonIncentive
);
}
/**
* @dev Gets some details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return number of all proposal solutions
* @return amount of votes
*/
function proposalDetails(uint _proposalId) external view returns (uint, uint, uint) {
return (
_proposalId,
allProposalSolutions[_proposalId].length,
proposalVoteTally[_proposalId].voters
);
}
/**
* @dev Gets solution action on a proposal
* @param _proposalId whose details we want
* @param _solution whose details we want
* @return action of a solution on a proposal
*/
function getSolutionAction(uint _proposalId, uint _solution) external view returns (uint, bytes memory) {
return (
_solution,
allProposalSolutions[_proposalId][_solution]
);
}
/**
* @dev Gets length of propsal
* @return length of propsal
*/
function getProposalLength() external view returns (uint) {
return totalProposals;
}
/**
* @dev Get followers of an address
* @return get followers of an address
*/
function getFollowers(address _add) external view returns (uint[] memory) {
return leaderDelegation[_add];
}
/**
* @dev Gets pending rewards of a member
* @param _memberAddress in concern
* @return amount of pending reward
*/
function getPendingReward(address _memberAddress)
public view returns (uint pendingDAppReward)
{
uint delegationId = followerDelegation[_memberAddress];
address leader;
uint lastUpd;
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) {
if (allVotes[allVotesByMember[leader][i]].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) {
if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) {
proposalId = allVotes[allVotesByMember[leader][i]].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus
> uint(ProposalStatus.VotingStarted)) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
}
}
}
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "GOVHOLD") {
tokenHoldingTime = val * 1 days;
} else if (code == "MAXFOL") {
maxFollowers = val;
} else if (code == "MAXDRFT") {
maxDraftTime = val * 1 days;
} else if (code == "EPTIME") {
ms.updatePauseTime(val * 1 days);
} else if (code == "ACWT") {
actionWaitingTime = val * 1 hours;
} else {
revert("Invalid code");
}
}
/**
* @dev Updates all dependency addresses to latest ones from Master
*/
function changeDependentContractAddress() public {
tokenInstance = TokenController(ms.dAppLocker());
memberRole = MemberRoles(ms.getLatestAddress("MR"));
proposalCategory = ProposalCategory(ms.getLatestAddress("PC"));
}
/**
* @dev Checks if msg.sender is allowed to create a proposal under given category
*/
function allowedToCreateProposal(uint category) public view returns (bool check) {
if (category == 0)
return true;
uint[] memory mrAllowed;
(,,,, mrAllowed,,) = proposalCategory.category(category);
for (uint i = 0; i < mrAllowed.length; i++) {
if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i]))
return true;
}
}
/**
* @dev Checks if an address is already delegated
* @param _add in concern
* @return bool value if the address is delegated or not
*/
function alreadyDelegated(address _add) public view returns (bool delegated) {
for (uint i = 0; i < leaderDelegation[_add].length; i++) {
if (allDelegation[leaderDelegation[_add][i]].leader == _add) {
return true;
}
}
}
/**
* @dev Checks If the proposal voting time is up and it's ready to close
* i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise!
* @param _proposalId Proposal id to which closing value is being checked
*/
function canCloseProposal(uint _proposalId)
public
view
returns (uint)
{
uint dateUpdate;
uint pStatus;
uint _closingTime;
uint _roleId;
uint majority;
pStatus = allProposalData[_proposalId].propStatus;
dateUpdate = allProposalData[_proposalId].dateUpd;
(, _roleId, majority, , , _closingTime,) = proposalCategory.category(allProposalData[_proposalId].category);
if (
pStatus == uint(ProposalStatus.VotingStarted)
) {
uint numberOfMembers = memberRole.numberOfMembers(_roleId);
if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority
|| proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers
|| dateUpdate.add(_closingTime) <= now) {
return 1;
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters
|| dateUpdate.add(_closingTime) <= now)
return 1;
}
} else if (pStatus > uint(ProposalStatus.VotingStarted)) {
return 2;
} else {
return 0;
}
}
/**
* @dev Gets Id of member role allowed to categorize the proposal
* @return roleId allowed to categorize the proposal
*/
function allowedToCatgorize() public view returns (uint roleId) {
return roleIdAllowedToCatgorize;
}
/**
* @dev Gets vote tally data
* @param _proposalId in concern
* @param _solution of a proposal id
* @return member vote value
* @return advisory board vote value
* @return amount of votes
*/
function voteTallyData(uint _proposalId, uint _solution) public view returns (uint, uint, uint) {
return (proposalVoteTally[_proposalId].memberVoteValue[_solution],
proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters);
}
/**
* @dev Internal call to create proposal
* @param _proposalTitle of proposal
* @param _proposalSD is short description of proposal
* @param _proposalDescHash IPFS hash value of propsal
* @param _categoryId of proposal
*/
function _createProposal(
string memory _proposalTitle,
string memory _proposalSD,
string memory _proposalDescHash,
uint _categoryId
)
internal
{
require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0);
uint _proposalId = totalProposals;
allProposalData[_proposalId].owner = msg.sender;
allProposalData[_proposalId].dateUpd = now;
allProposalSolutions[_proposalId].push("");
totalProposals++;
emit Proposal(
msg.sender,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
if (_categoryId > 0)
_categorizeProposal(_proposalId, _categoryId, 0);
}
/**
* @dev Internal call to categorize a proposal
* @param _proposalId of proposal
* @param _categoryId of proposal
* @param _incentive is commonIncentive
*/
function _categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
internal
{
require(
_categoryId > 0 && _categoryId < proposalCategory.totalCategories(),
"Invalid category"
);
allProposalData[_proposalId].category = _categoryId;
allProposalData[_proposalId].commonIncentive = _incentive;
allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution);
emit ProposalCategorized(_proposalId, msg.sender, _categoryId);
}
/**
* @dev Internal call to add solution to a proposal
* @param _proposalId in concern
* @param _action on that solution
* @param _solutionHash string value
*/
function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash)
internal
{
allProposalSolutions[_proposalId].push(_action);
emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now);
}
/**
* @dev Internal call to add solution and open proposal for voting
*/
function _proposalSubmission(
uint _proposalId,
string memory _solutionHash,
bytes memory _action
)
internal
{
uint _categoryId = allProposalData[_proposalId].category;
if (proposalCategory.categoryActionHashes(_categoryId).length == 0) {
require(keccak256(_action) == keccak256(""));
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
_addSolution(
_proposalId,
_action,
_solutionHash
);
_updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted));
(, , , , , uint closingTime,) = proposalCategory.category(_categoryId);
emit CloseProposalOnTime(_proposalId, closingTime.add(now));
}
/**
* @dev Internal call to submit vote
* @param _proposalId of proposal in concern
* @param _solution for that proposal
*/
function _submitVote(uint _proposalId, uint _solution) internal {
uint delegationId = followerDelegation[msg.sender];
uint mrSequence;
uint majority;
uint closingTime;
(, mrSequence, majority, , , closingTime,) = proposalCategory.category(allProposalData[_proposalId].category);
require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed");
require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed");
require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) &&
_checkLastUpd(allDelegation[delegationId].lastUpd)));
require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized");
uint totalVotes = allVotes.length;
allVotesByMember[msg.sender].push(totalVotes);
memberProposalVote[msg.sender][_proposalId] = totalVotes;
allVotes.push(ProposalVote(msg.sender, _proposalId, now));
emit Vote(msg.sender, _proposalId, totalVotes, now, _solution);
if (mrSequence == uint(MemberRoles.Role.Owner)) {
if (_solution == 1)
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner);
else
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
} else {
uint numberOfMembers = memberRole.numberOfMembers(mrSequence);
_setVoteTally(_proposalId, _solution, mrSequence);
if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers)
>= majority
|| (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) {
emit VoteCast(_proposalId);
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters)
emit VoteCast(_proposalId);
}
}
}
/**
* @dev Internal call to set vote tally of a proposal
* @param _proposalId of proposal in concern
* @param _solution of proposal in concern
* @param mrSequence number of members for a role
*/
function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal
{
uint categoryABReq;
uint isSpecialResolution;
(, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category);
if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) ||
mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
proposalVoteTally[_proposalId].abVoteValue[_solution]++;
}
tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime);
if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) {
uint voteWeight;
uint voters = 1;
uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender);
uint totalSupply = tokenInstance.totalSupply();
if (isSpecialResolution == 1) {
voteWeight = tokenBalance.add(10 ** 18);
} else {
voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18);
}
DelegateVote memory delegationData;
for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) {
delegationData = allDelegation[leaderDelegation[msg.sender][i]];
if (delegationData.leader == msg.sender &&
_checkLastUpd(delegationData.lastUpd)) {
if (memberRole.checkRole(delegationData.follower, mrSequence)) {
tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower);
tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime);
voters++;
if (isSpecialResolution == 1) {
voteWeight = voteWeight.add(tokenBalance.add(10 ** 18));
} else {
voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18));
}
}
}
}
proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight);
proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters;
}
}
/**
* @dev Gets minimum of two numbers
* @param a one of the two numbers
* @param b one of the two numbers
* @return minimum number out of the two
*/
function _minOf(uint a, uint b) internal pure returns (uint res) {
res = a;
if (res > b)
res = b;
}
/**
* @dev Check the time since last update has exceeded token holding time or not
* @param _lastUpd is last update time
* @return the bool which tells if the time since last update has exceeded token holding time or not
*/
function _checkLastUpd(uint _lastUpd) internal view returns (bool) {
return (now - _lastUpd) > tokenHoldingTime;
}
/**
* @dev Checks if the vote count against any solution passes the threshold value or not.
*/
function _checkForThreshold(uint _proposalId, uint _category) internal view returns (bool check) {
uint categoryQuorumPerc;
uint roleAuthorized;
(, roleAuthorized, , categoryQuorumPerc, , ,) = proposalCategory.category(_category);
check = ((proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1]))
.mul(100))
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18)
)
) >= categoryQuorumPerc;
}
/**
* @dev Called when vote majority is reached
* @param _proposalId of proposal in concern
* @param _status of proposal in concern
* @param category of proposal in concern
* @param max vote value of proposal in concern
*/
function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal {
allProposalData[_proposalId].finalVerdict = max;
_updateProposalStatus(_proposalId, _status);
emit ProposalAccepted(_proposalId);
if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) {
if (role == MemberRoles.Role.AdvisoryBoard) {
_triggerAction(_proposalId, category);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
proposalExecutionTime[_proposalId] = actionWaitingTime.add(now);
}
}
}
/**
* @dev Internal function to trigger action of accepted proposal
*/
function _triggerAction(uint _proposalId, uint _categoryId) internal {
proposalActionStatus[_proposalId] = uint(ActionStatus.Executed);
bytes2 contractName;
address actionAddress;
bytes memory _functionHash;
(, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId);
if (contractName == "MS") {
actionAddress = address(ms);
} else if (contractName != "EX") {
actionAddress = ms.getLatestAddress(contractName);
}
// solhint-disable-next-line avoid-low-level-calls
(bool actionStatus,) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1]));
if (actionStatus) {
emit ActionSuccess(_proposalId);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
emit ActionFailed(_proposalId);
}
}
/**
* @dev Internal call to update proposal status
* @param _proposalId of proposal in concern
* @param _status of proposal to set
*/
function _updateProposalStatus(uint _proposalId, uint _status) internal {
if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) {
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
allProposalData[_proposalId].dateUpd = now;
allProposalData[_proposalId].propStatus = _status;
}
/**
* @dev Internal call to undelegate a follower
* @param _follower is address of follower to undelegate
*/
function _unDelegate(address _follower) internal {
uint followerId = followerDelegation[_follower];
if (followerId > 0) {
followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1);
allDelegation[followerId].leader = address(0);
allDelegation[followerId].lastUpd = now;
lastRewardClaimed[_follower] = allVotesByMember[_follower].length;
}
}
/**
* @dev Internal call to close member voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeMemberVote(uint _proposalId, uint category) internal {
uint isSpecialResolution;
uint abMaj;
(, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category);
if (isSpecialResolution == 1) {
uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10 ** 18)
));
if (acceptedVotePerc >= specialResolutionMajPerc) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
} else {
if (_checkForThreshold(_proposalId, category)) {
uint majorityVote;
(,, majorityVote,,,,) = proposalCategory.category(category);
if (
((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100))
.div(proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1])
))
>= majorityVote
) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
}
} else {
if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
if (proposalVoteTally[_proposalId].voters > 0) {
tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive);
}
}
/**
* @dev Internal call to close advisory board voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal {
uint _majorityVote;
MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard;
(,, _majorityVote,,,,) = proposalCategory.category(category);
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/MasterAware.sol";
import "../cover/QuotationData.sol";
import "./NXMToken.sol";
import "./TokenController.sol";
import "./TokenData.sol";
contract TokenFunctions is MasterAware {
using SafeMath for uint;
TokenController public tc;
NXMToken public tk;
QuotationData public qd;
event BurnCATokens(uint claimId, address addr, uint amount);
/**
* @dev to get the all the cover locked tokens of a user
* @param _of is the user address in concern
* @return amount locked
*/
function getUserAllLockedCNTokens(address _of) external view returns (uint) {
uint[] memory coverIds = qd.getAllCoversOfUser(_of);
uint total;
for (uint i = 0; i < coverIds.length; i++) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverIds[i]));
uint coverNote = tc.tokensLocked(_of, reason);
total = total.add(coverNote);
}
return total;
}
/**
* @dev Change Dependent Contract Address
*/
function changeDependentContractAddress() public {
tc = TokenController(master.getLatestAddress("TC"));
tk = NXMToken(master.tokenAddress());
qd = QuotationData(master.getLatestAddress("QD"));
}
/**
* @dev Burns tokens used for fraudulent voting against a claim
* @param claimid Claim Id.
* @param _value number of tokens to be burned
* @param _of Claim Assessor's address.
*/
function burnCAToken(uint claimid, uint _value, address _of) external onlyGovernance {
tc.burnLockedTokens(_of, "CLA", _value);
emit BurnCATokens(claimid, _of, _value);
}
/**
* @dev to check if a member is locked for member vote
* @param _of is the member address in concern
* @return the boolean status
*/
function isLockedForMemberVote(address _of) public view returns (bool) {
return now < tk.isLockedForMV(_of);
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../capital/Pool.sol";
import "../claims/ClaimsReward.sol";
import "../token/NXMToken.sol";
import "../token/TokenController.sol";
import "../token/TokenFunctions.sol";
import "./ClaimsData.sol";
import "./Incidents.sol";
contract Claims is Iupgradable {
using SafeMath for uint;
TokenController internal tc;
ClaimsReward internal cr;
Pool internal p1;
ClaimsData internal cd;
TokenData internal td;
QuotationData internal qd;
Incidents internal incidents;
uint private constant DECIMAL1E18 = uint(10) ** 18;
/**
* @dev Sets the status of claim using claim id.
* @param claimId claim id.
* @param stat status to be set.
*/
function setClaimStatus(uint claimId, uint stat) external onlyInternal {
_setClaimStatus(claimId, stat);
}
/**
* @dev Calculates total amount that has been used to assess a claim.
* Computaion:Adds acceptCA(tokens used for voting in favor of a claim)
* denyCA(tokens used for voting against a claim) * current token price.
* @param claimId Claim Id.
* @param member Member type 0 -> Claim Assessors, else members.
* @return tokens Total Amount used in Claims assessment.
*/
function getCATokens(uint claimId, uint member) external view returns (uint tokens) {
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 currency = qd.getCurrencyOfCover(coverId);
address asset = cr.getCurrencyAssetAddress(currency);
uint tokenx1e18 = p1.getTokenPrice(asset);
uint accept;
uint deny;
if (member == 0) {
(, accept, deny) = cd.getClaimsTokenCA(claimId);
} else {
(, accept, deny) = cd.getClaimsTokenMV(claimId);
}
tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens)
}
/**
* Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
td = TokenData(ms.getLatestAddress("TD"));
tc = TokenController(ms.getLatestAddress("TC"));
p1 = Pool(ms.getLatestAddress("P1"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
cd = ClaimsData(ms.getLatestAddress("CD"));
qd = QuotationData(ms.getLatestAddress("QD"));
incidents = Incidents(ms.getLatestAddress("IC"));
}
/**
* @dev Submits a claim for a given cover note.
* Adds claim to queue incase of emergency pause else directly submits the claim.
* @param coverId Cover Id.
*/
function submitClaim(uint coverId) external {
_submitClaim(coverId, msg.sender);
}
function submitClaimForMember(uint coverId, address member) external onlyInternal {
_submitClaim(coverId, member);
}
function _submitClaim(uint coverId, address member) internal {
require(!ms.isPause(), "Claims: System is paused");
(/* id */, address contractAddress) = qd.getscAddressOfCover(coverId);
address token = incidents.coveredToken(contractAddress);
require(token == address(0), "Claims: Product type does not allow claims");
address coverOwner = qd.getCoverMemberAddress(coverId);
require(coverOwner == member, "Claims: Not cover owner");
uint expirationDate = qd.getValidityOfCover(coverId);
uint gracePeriod = tc.claimSubmissionGracePeriod();
require(expirationDate.add(gracePeriod) > now, "Claims: Grace period has expired");
tc.markCoverClaimOpen(coverId);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted));
uint claimId = cd.actualClaimLength();
cd.addClaim(claimId, coverId, coverOwner, now);
cd.callClaimEvent(coverId, coverOwner, claimId, now);
}
// solhint-disable-next-line no-empty-blocks
function submitClaimAfterEPOff() external pure {}
/**
* @dev Castes vote for members who have tokens locked under Claims Assessment
* @param claimId claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now);
uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime()));
require(tokens > 0);
uint stat;
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat == 0);
require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0);
td.bookCATokens(msg.sender);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict);
uint voteLength = cd.getAllVoteLength();
cd.addClaimVoteCA(claimId, voteLength);
cd.setUserClaimVoteCA(msg.sender, claimId, voteLength);
cd.setClaimTokensCA(claimId, verdict, tokens);
tc.extendLockOf(msg.sender, "CLA", td.lockCADays());
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
/**
* @dev Submits a member vote for assessing a claim.
* Tokens other than those locked under Claims
* Assessment can be used to cast a vote for a given claim id.
* @param claimId Selected claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
uint stat;
uint tokens = tc.totalBalanceOf(msg.sender);
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat >= 1 && stat <= 5);
require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict);
tc.lockForMemberVote(msg.sender, td.lockMVDays());
uint voteLength = cd.getAllVoteLength();
cd.addClaimVotemember(claimId, voteLength);
cd.setUserClaimVoteMember(msg.sender, claimId, voteLength);
cd.setClaimTokensMV(claimId, verdict, tokens);
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
// solhint-disable-next-line no-empty-blocks
function pauseAllPendingClaimsVoting() external pure {}
// solhint-disable-next-line no-empty-blocks
function startAllPendingClaimsVoting() external pure {}
/**
* @dev Checks if voting of a claim should be closed or not.
* @param claimId Claim Id.
* @return close 1 -> voting should be closed, 0 -> if voting should not be closed,
* -1 -> voting has already been closed.
*/
function checkVoteClosing(uint claimId) public view returns (int8 close) {
close = 0;
uint status;
(, status) = cd.getClaimStatusNumber(claimId);
uint dateUpd = cd.getClaimDateUpd(claimId);
if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) {
if (cd.getClaimState12Count(claimId) < 60)
close = 1;
}
if (status > 5 && status != 12) {
close = - 1;
} else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) {
close = 1;
} else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) {
close = 0;
} else if (status == 0 || (status >= 1 && status <= 5)) {
close = _checkVoteClosingFinal(claimId, status);
}
}
/**
* @dev Checks if voting of a claim should be closed or not.
* Internally called by checkVoteClosing method
* for Claims whose status number is 0 or status number lie between 2 and 6.
* @param claimId Claim Id.
* @param status Current status of claim.
* @return close 1 if voting should be closed,0 in case voting should not be closed,
* -1 if voting has already been closed.
*/
function _checkVoteClosingFinal(uint claimId, uint status) internal view returns (int8 close) {
close = 0;
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 currency = qd.getCurrencyOfCover(coverId);
address asset = cr.getCurrencyAssetAddress(currency);
uint tokenx1e18 = p1.getTokenPrice(asset);
uint accept;
uint deny;
(, accept, deny) = cd.getClaimsTokenCA(claimId);
uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
(, accept, deny) = cd.getClaimsTokenMV(claimId);
uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18);
if (status == 0 && caTokens >= sumassured.mul(10)) {
close = 1;
} else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) {
close = 1;
}
}
/**
* @dev Changes the status of an existing claim id, based on current
* status and current conditions of the system
* @param claimId Claim Id.
* @param stat status number.
*/
function _setClaimStatus(uint claimId, uint stat) internal {
uint origstat;
uint state12Count;
uint dateUpd;
uint coverId;
(, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId);
(, origstat) = cd.getClaimStatusNumber(claimId);
if (stat == 12 && origstat == 12) {
cd.updateState12Count(claimId, 1);
}
cd.setClaimStatus(claimId, stat);
if (state12Count >= 60 && stat == 12) {
cd.setClaimStatus(claimId, 13);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied));
}
cd.setClaimdateUpd(claimId, now);
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../claims/ClaimsReward.sol";
import "../cover/QuotationData.sol";
import "../token/TokenController.sol";
import "../token/TokenData.sol";
import "../token/TokenFunctions.sol";
import "./Governance.sol";
import "./external/Governed.sol";
contract MemberRoles is Governed, Iupgradable {
TokenController public tc;
TokenData internal td;
QuotationData internal qd;
ClaimsReward internal cr;
Governance internal gv;
TokenFunctions internal tf;
NXMToken public tk;
struct MemberRoleDetails {
uint memberCounter;
mapping(address => bool) memberActive;
address[] memberAddress;
address authorized;
}
enum Role {UnAssigned, AdvisoryBoard, Member, Owner}
event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription);
event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp);
event ClaimPayoutAddressSet(address indexed member, address indexed payoutAddress);
MemberRoleDetails[] internal memberRoleData;
bool internal constructorCheck;
uint public maxABCount;
bool public launched;
uint public launchedOn;
mapping (address => address payable) internal claimPayoutAddress;
modifier checkRoleAuthority(uint _memberRoleId) {
if (memberRoleData[_memberRoleId].authorized != address(0))
require(msg.sender == memberRoleData[_memberRoleId].authorized);
else
require(isAuthorizedToGovern(msg.sender), "Not Authorized");
_;
}
/**
* @dev to swap advisory board member
* @param _newABAddress is address of new AB member
* @param _removeAB is advisory board member to be removed
*/
function swapABMember(
address _newABAddress,
address _removeAB
)
external
checkRoleAuthority(uint(Role.AdvisoryBoard)) {
_updateRole(_newABAddress, uint(Role.AdvisoryBoard), true);
_updateRole(_removeAB, uint(Role.AdvisoryBoard), false);
}
/**
* @dev to swap the owner address
* @param _newOwnerAddress is the new owner address
*/
function swapOwner(
address _newOwnerAddress
)
external {
require(msg.sender == address(ms));
_updateRole(ms.owner(), uint(Role.Owner), false);
_updateRole(_newOwnerAddress, uint(Role.Owner), true);
}
/**
* @dev is used to add initital advisory board members
* @param abArray is the list of initial advisory board members
*/
function addInitialABMembers(address[] calldata abArray) external onlyOwner {
//Ensure that NXMaster has initialized.
require(ms.masterInitialized());
require(maxABCount >=
SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length)
);
//AB count can't exceed maxABCount
for (uint i = 0; i < abArray.length; i++) {
require(checkRole(abArray[i], uint(MemberRoles.Role.Member)));
_updateRole(abArray[i], uint(Role.AdvisoryBoard), true);
}
}
/**
* @dev to change max number of AB members allowed
* @param _val is the new value to be set
*/
function changeMaxABCount(uint _val) external onlyInternal {
maxABCount = _val;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
td = TokenData(ms.getLatestAddress("TD"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
tk = NXMToken(ms.tokenAddress());
tc = TokenController(ms.getLatestAddress("TC"));
}
/**
* @dev to change the master address
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0)) {
require(masterAddress == msg.sender);
}
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev to initiate the member roles
* @param _firstAB is the address of the first AB member
* @param memberAuthority is the authority (role) of the member
*/
function memberRolesInitiate(address _firstAB, address memberAuthority) public {
require(!constructorCheck);
_addInitialMemberRoles(_firstAB, memberAuthority);
constructorCheck = true;
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function addRole(//solhint-disable-line
bytes32 _roleName,
string memory _roleDescription,
address _authorized
)
public
onlyAuthorizedToGovern {
_addRole(_roleName, _roleDescription, _authorized);
}
/// @dev Assign or Delete a member from specific role.
/// @param _memberAddress Address of Member
/// @param _roleId RoleId to update
/// @param _active active is set to be True if we want to assign this role to member, False otherwise!
function updateRole(//solhint-disable-line
address _memberAddress,
uint _roleId,
bool _active
)
public
checkRoleAuthority(_roleId) {
_updateRole(_memberAddress, _roleId, _active);
}
/**
* @dev to add members before launch
* @param userArray is list of addresses of members
* @param tokens is list of tokens minted for each array element
*/
function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner {
require(!launched);
for (uint i = 0; i < userArray.length; i++) {
require(!ms.isMember(userArray[i]));
tc.addToWhitelist(userArray[i]);
_updateRole(userArray[i], uint(Role.Member), true);
tc.mint(userArray[i], tokens[i]);
}
launched = true;
launchedOn = now;
}
/**
* @dev Called by user to pay joining membership fee
*/
function payJoiningFee(address _userAddress) public payable {
require(_userAddress != address(0));
require(!ms.isPause(), "Emergency Pause Applied");
if (msg.sender == address(ms.getLatestAddress("QT"))) {
require(td.walletAddress() != address(0), "No walletAddress present");
tc.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(msg.value);
} else {
require(!qd.refundEligible(_userAddress));
require(!ms.isMember(_userAddress));
require(msg.value == td.joiningFee());
qd.setRefundEligible(_userAddress, true);
}
}
/**
* @dev to perform kyc verdict
* @param _userAddress whose kyc is being performed
* @param verdict of kyc process
*/
function kycVerdict(address payable _userAddress, bool verdict) public {
require(msg.sender == qd.kycAuthAddress());
require(!ms.isPause());
require(_userAddress != address(0));
require(!ms.isMember(_userAddress));
require(qd.refundEligible(_userAddress));
if (verdict) {
qd.setRefundEligible(_userAddress, false);
uint fee = td.joiningFee();
tc.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(fee); // solhint-disable-line
} else {
qd.setRefundEligible(_userAddress, false);
_userAddress.transfer(td.joiningFee()); // solhint-disable-line
}
}
/**
* @dev withdraws membership for msg.sender if currently a member.
*/
function withdrawMembership() public {
require(!ms.isPause() && ms.isMember(msg.sender));
require(tc.totalLockedBalance(msg.sender) == 0); // solhint-disable-line
require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment).
gv.removeDelegation(msg.sender);
tc.burnFrom(msg.sender, tk.balanceOf(msg.sender));
_updateRole(msg.sender, uint(Role.Member), false);
tc.removeFromWhitelist(msg.sender); // need clarification on whitelist
if (claimPayoutAddress[msg.sender] != address(0)) {
claimPayoutAddress[msg.sender] = address(0);
emit ClaimPayoutAddressSet(msg.sender, address(0));
}
}
/**
* @dev switches membership for msg.sender to the specified address.
* @param newAddress address of user to forward membership.
*/
function switchMembership(address newAddress) external {
_switchMembership(msg.sender, newAddress);
tk.transferFrom(msg.sender, newAddress, tk.balanceOf(msg.sender));
}
function switchMembershipOf(address member, address newAddress) external onlyInternal {
_switchMembership(member, newAddress);
}
/**
* @dev switches membership for member to the specified address.
* @param newAddress address of user to forward membership.
*/
function _switchMembership(address member, address newAddress) internal {
require(!ms.isPause() && ms.isMember(member) && !ms.isMember(newAddress));
require(tc.totalLockedBalance(member) == 0); // solhint-disable-line
require(!tf.isLockedForMemberVote(member)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(member) == 0); // No pending reward to be claimed(claim assesment).
gv.removeDelegation(member);
tc.addToWhitelist(newAddress);
_updateRole(newAddress, uint(Role.Member), true);
_updateRole(member, uint(Role.Member), false);
tc.removeFromWhitelist(member);
address payable previousPayoutAddress = claimPayoutAddress[member];
if (previousPayoutAddress != address(0)) {
address payable storedAddress = previousPayoutAddress == newAddress ? address(0) : previousPayoutAddress;
claimPayoutAddress[member] = address(0);
claimPayoutAddress[newAddress] = storedAddress;
// emit event for old address reset
emit ClaimPayoutAddressSet(member, address(0));
if (storedAddress != address(0)) {
// emit event for setting the payout address on the new member address if it's non zero
emit ClaimPayoutAddressSet(newAddress, storedAddress);
}
}
emit switchedMembership(member, newAddress, now);
}
function getClaimPayoutAddress(address payable _member) external view returns (address payable) {
address payable payoutAddress = claimPayoutAddress[_member];
return payoutAddress != address(0) ? payoutAddress : _member;
}
function setClaimPayoutAddress(address payable _address) external {
require(!ms.isPause(), "system is paused");
require(ms.isMember(msg.sender), "sender is not a member");
require(_address != msg.sender, "should be different than the member address");
claimPayoutAddress[msg.sender] = _address;
emit ClaimPayoutAddressSet(msg.sender, _address);
}
/// @dev Return number of member roles
function totalRoles() public view returns (uint256) {//solhint-disable-line
return memberRoleData.length;
}
/// @dev Change Member Address who holds the authority to Add/Delete any member from specific role.
/// @param _roleId roleId to update its Authorized Address
/// @param _newAuthorized New authorized address against role id
function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) {//solhint-disable-line
memberRoleData[_roleId].authorized = _newAuthorized;
}
/// @dev Gets the member addresses assigned by a specific role
/// @param _memberRoleId Member role id
/// @return roleId Role id
/// @return allMemberAddress Member addresses of specified role id
function members(uint _memberRoleId) public view returns (uint, address[] memory memberArray) {//solhint-disable-line
uint length = memberRoleData[_memberRoleId].memberAddress.length;
uint i;
uint j = 0;
memberArray = new address[](memberRoleData[_memberRoleId].memberCounter);
for (i = 0; i < length; i++) {
address member = memberRoleData[_memberRoleId].memberAddress[i];
if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) {//solhint-disable-line
memberArray[j] = member;
j++;
}
}
return (_memberRoleId, memberArray);
}
/// @dev Gets all members' length
/// @param _memberRoleId Member role id
/// @return memberRoleData[_memberRoleId].memberCounter Member length
function numberOfMembers(uint _memberRoleId) public view returns (uint) {//solhint-disable-line
return memberRoleData[_memberRoleId].memberCounter;
}
/// @dev Return member address who holds the right to add/remove any member from specific role.
function authorized(uint _memberRoleId) public view returns (address) {//solhint-disable-line
return memberRoleData[_memberRoleId].authorized;
}
/// @dev Get All role ids array that has been assigned to a member so far.
function roles(address _memberAddress) public view returns (uint[] memory) {//solhint-disable-line
uint length = memberRoleData.length;
uint[] memory assignedRoles = new uint[](length);
uint counter = 0;
for (uint i = 1; i < length; i++) {
if (memberRoleData[i].memberActive[_memberAddress]) {
assignedRoles[counter] = i;
counter++;
}
}
return assignedRoles;
}
/// @dev Returns true if the given role id is assigned to a member.
/// @param _memberAddress Address of member
/// @param _roleId Checks member's authenticity with the roleId.
/// i.e. Returns true if this roleId is assigned to member
function checkRole(address _memberAddress, uint _roleId) public view returns (bool) {//solhint-disable-line
if (_roleId == uint(Role.UnAssigned))
return true;
else
if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line
return true;
else
return false;
}
/// @dev Return total number of members assigned against each role id.
/// @return totalMembers Total members in particular role id
function getMemberLengthForAllRoles() public view returns (uint[] memory totalMembers) {//solhint-disable-line
totalMembers = new uint[](memberRoleData.length);
for (uint i = 0; i < memberRoleData.length; i++) {
totalMembers[i] = numberOfMembers(i);
}
}
/**
* @dev to update the member roles
* @param _memberAddress in concern
* @param _roleId the id of role
* @param _active if active is true, add the member, else remove it
*/
function _updateRole(address _memberAddress,
uint _roleId,
bool _active) internal {
// require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically");
if (_active) {
require(!memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1);
memberRoleData[_roleId].memberActive[_memberAddress] = true;
memberRoleData[_roleId].memberAddress.push(_memberAddress);
} else {
require(memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1);
delete memberRoleData[_roleId].memberActive[_memberAddress];
}
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function _addRole(
bytes32 _roleName,
string memory _roleDescription,
address _authorized
) internal {
emit MemberRole(memberRoleData.length, _roleName, _roleDescription);
memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized));
}
/**
* @dev to check if member is in the given member array
* @param _memberAddress in concern
* @param memberArray in concern
* @return boolean to represent the presence
*/
function _checkMemberInArray(
address _memberAddress,
address[] memory memberArray
)
internal
pure
returns (bool memberExists)
{
uint i;
for (i = 0; i < memberArray.length; i++) {
if (memberArray[i] == _memberAddress) {
memberExists = true;
break;
}
}
}
/**
* @dev to add initial member roles
* @param _firstAB is the member address to be added
* @param memberAuthority is the member authority(role) to be added for
*/
function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal {
maxABCount = 5;
_addRole("Unassigned", "Unassigned", address(0));
_addRole(
"Advisory Board",
"Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line
address(0)
);
_addRole(
"Member",
"Represents all users of Mutual.", //solhint-disable-line
memberAuthority
);
_addRole(
"Owner",
"Represents Owner of Mutual.", //solhint-disable-line
address(0)
);
// _updateRole(_firstAB, uint(Role.AdvisoryBoard), true);
_updateRole(_firstAB, uint(Role.Owner), true);
// _updateRole(_firstAB, uint(Role.Member), true);
launchedOn = 0;
}
function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) {
address memberAddress = memberRoleData[_memberRoleId].memberAddress[index];
return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]);
}
function membersLength(uint _memberRoleId) external view returns (uint) {
return memberRoleData[_memberRoleId].memberAddress.length;
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../../abstract/Iupgradable.sol";
import "./MemberRoles.sol";
import "./external/Governed.sol";
import "./external/IProposalCategory.sol";
contract ProposalCategory is Governed, IProposalCategory, Iupgradable {
bool public constructorCheck;
MemberRoles internal mr;
struct CategoryStruct {
uint memberRoleToVote;
uint majorityVotePerc;
uint quorumPerc;
uint[] allowedToCreateProposal;
uint closingTime;
uint minStake;
}
struct CategoryAction {
uint defaultIncentive;
address contractAddress;
bytes2 contractName;
}
CategoryStruct[] internal allCategory;
mapping(uint => CategoryAction) internal categoryActionData;
mapping(uint => uint) public categoryABReq;
mapping(uint => uint) public isSpecialResolution;
mapping(uint => bytes) public categoryActionHashes;
bool public categoryActionHashUpdated;
/**
* @dev Adds new category (Discontinued, moved functionality to newCategory)
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
) external {}
/**
* @dev Initiates Default settings for Proposal Category contract (Adding default categories)
*/
function proposalCategoryInitiate() external {}
/**
* @dev Initiates Default action function hashes for existing categories
* To be called after the contract has been upgraded by governance
*/
function updateCategoryActionHashes() external onlyOwner {
require(!categoryActionHashUpdated, "Category action hashes already updated");
categoryActionHashUpdated = true;
categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)");
categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)");
categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line
categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line
categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)");
categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()");
categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)");
categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)");
categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)");
categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)");
categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)"); // solhint-disable-line
categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)");
categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)");
categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)");
categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)");
categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)");
categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)");
categoryActionHashes[29] = abi.encodeWithSignature("upgradeMultipleContracts(bytes2[],address[])");
categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)");
categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)");
categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)"); // solhint-disable-line
categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()");
}
/**
* @dev Gets Total number of categories added till now
*/
function totalCategories() external view returns (uint) {
return allCategory.length;
}
/**
* @dev Gets category details
*/
function category(uint _categoryId) external view returns (uint, uint, uint, uint, uint[] memory, uint, uint) {
return (
_categoryId,
allCategory[_categoryId].memberRoleToVote,
allCategory[_categoryId].majorityVotePerc,
allCategory[_categoryId].quorumPerc,
allCategory[_categoryId].allowedToCreateProposal,
allCategory[_categoryId].closingTime,
allCategory[_categoryId].minStake
);
}
/**
* @dev Gets category ab required and isSpecialResolution
* @return the category id
* @return if AB voting is required
* @return is category a special resolution
*/
function categoryExtendedData(uint _categoryId) external view returns (uint, uint, uint) {
return (
_categoryId,
categoryABReq[_categoryId],
isSpecialResolution[_categoryId]
);
}
/**
* @dev Gets the category acion details
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
*/
function categoryAction(uint _categoryId) external view returns (uint, address, bytes2, uint) {
return (
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive
);
}
/**
* @dev Gets the category acion details of a category id
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
* @return action function hash
*/
function categoryActionDetails(uint _categoryId) external view returns (uint, address, bytes2, uint, bytes memory) {
return (
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive,
categoryActionHashes[_categoryId]
);
}
/**
* @dev Updates dependant contract addresses
*/
function changeDependentContractAddress() public {
mr = MemberRoles(ms.getLatestAddress("MR"));
}
/**
* @dev Adds new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function newCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
_addCategory(
_name,
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_actionHash,
_contractAddress,
_contractName,
_incentives
);
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash);
}
}
/**
* @dev Changes the master address and update it's instance
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0))
require(masterAddress == msg.sender);
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev Updates category details (Discontinued, moved functionality to editCategory)
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
) public {}
/**
* @dev Updates category details
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function editCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
delete categoryActionHashes[_categoryId];
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash);
}
allCategory[_categoryId].memberRoleToVote = _memberRoleToVote;
allCategory[_categoryId].majorityVotePerc = _majorityVotePerc;
allCategory[_categoryId].closingTime = _closingTime;
allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal;
allCategory[_categoryId].minStake = _incentives[0];
allCategory[_categoryId].quorumPerc = _quorumPerc;
categoryActionData[_categoryId].defaultIncentive = _incentives[1];
categoryActionData[_categoryId].contractName = _contractName;
categoryActionData[_categoryId].contractAddress = _contractAddress;
categoryABReq[_categoryId] = _incentives[2];
isSpecialResolution[_categoryId] = _incentives[3];
emit Category(_categoryId, _name, _actionHash);
}
/**
* @dev Internal call to add new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function _addCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
internal
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
allCategory.push(
CategoryStruct(
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_incentives[0]
)
);
uint categoryId = allCategory.length - 1;
categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName);
categoryABReq[categoryId] = _incentives[2];
isSpecialResolution[categoryId] = _incentives[3];
emit Category(categoryId, _name, _actionHash);
}
/**
* @dev Internal call to check if given roles are valid or not
*/
function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal)
internal view returns (uint) {
uint totalRoles = mr.totalRoles();
if (_memberRoleToVote >= totalRoles) {
return 0;
}
for (uint i = 0; i < _allowedToCreateProposal.length; i++) {
if (_allowedToCreateProposal[i] >= totalRoles) {
return 0;
}
}
return 1;
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract IGovernance {
event Proposal(
address indexed proposalOwner,
uint256 indexed proposalId,
uint256 dateAdd,
string proposalTitle,
string proposalSD,
string proposalDescHash
);
event Solution(
uint256 indexed proposalId,
address indexed solutionOwner,
uint256 indexed solutionId,
string solutionDescHash,
uint256 dateAdd
);
event Vote(
address indexed from,
uint256 indexed proposalId,
uint256 indexed voteId,
uint256 dateAdd,
uint256 solutionChosen
);
event RewardClaimed(
address indexed member,
uint gbtReward
);
/// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal.
event VoteCast (uint256 proposalId);
/// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can
/// call any offchain actions
event ProposalAccepted (uint256 proposalId);
/// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time.
event CloseProposalOnTime (
uint256 indexed proposalId,
uint256 time
);
/// @dev ActionSuccess event is called whenever an onchain action is executed.
event ActionSuccess (
uint256 proposalId
);
/// @dev Creates a new proposal
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external;
/// @dev Edits the details of an existing proposal and creates new version
/// @param _proposalId Proposal id that details needs to be updated
/// @param _proposalDescHash Proposal description hash having long and short description of proposal.
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external;
/// @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentives
)
external;
/// @dev Submit proposal with solution
/// @param _proposalId Proposal id
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Creates a new proposal with solution and votes for the solution
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Casts vote
/// @param _proposalId Proposal id
/// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution
function submitVote(uint _proposalId, uint _solutionChosen) external;
function closeProposal(uint _proposalId) external;
function claimReward(address _memberAddress, uint _maxRecords) external returns (uint pendingDAppReward);
function proposal(uint _proposalId)
external
view
returns (
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalReward
);
function canCloseProposal(uint _proposalId) public view returns (uint closeValue);
function allowedToCatgorize() public view returns (uint roleId);
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
interface IMaster {
function getLatestAddress(bytes2 _module) external view returns (address);
}
contract Governed {
address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract
/// @dev modifier that allows only the authorized addresses to execute the function
modifier onlyAuthorizedToGovern() {
IMaster ms = IMaster(masterAddress);
require(ms.getLatestAddress("GV") == msg.sender, "Not authorized");
_;
}
/// @dev checks if an address is authorized to govern
function isAuthorizedToGovern(address _toCheck) public view returns (bool) {
IMaster ms = IMaster(masterAddress);
return (ms.getLatestAddress("GV") == _toCheck);
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract IProposalCategory {
event Category(
uint indexed categoryId,
string categoryName,
string actionHash
);
/// @dev Adds new category
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
)
external;
/// @dev gets category details
function category(uint _categoryId)
external
view
returns (
uint categoryId,
uint memberRoleToVote,
uint majorityVotePerc,
uint quorumPerc,
uint[] memory allowedToCreateProposal,
uint closingTime,
uint minStake
);
///@dev gets category action details
function categoryAction(uint _categoryId)
external
view
returns (
uint categoryId,
address contractAddress,
bytes2 contractName,
uint defaultIncentive
);
/// @dev Gets Total number of categories added till now
function totalCategories() external view returns (uint numberOfCategories);
/// @dev Updates category details
/// @param _categoryId Category id that needs to be updated
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
public;
}
| * @dev Sets the reward claim status against a vote id. @param _voteid vote Id. @param claimed true if reward for vote is claimed, else false./ | function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal {
allvotes[_voteid].rewardClaimed = claimed;
}
| 2,578,256 | [
1,
2785,
326,
19890,
7516,
1267,
5314,
279,
12501,
612,
18,
225,
389,
25911,
350,
12501,
3124,
18,
225,
7516,
329,
638,
309,
19890,
364,
12501,
353,
7516,
329,
16,
469,
629,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
444,
17631,
1060,
9762,
329,
12,
11890,
389,
25911,
350,
16,
1426,
7516,
329,
13,
3903,
1338,
3061,
288,
203,
565,
777,
27800,
63,
67,
25911,
350,
8009,
266,
2913,
9762,
329,
273,
7516,
329,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0x4227a881a63c5134f4Ba76e3e235FB0e9a11832e/sources/DiamondHands.sol | Function that starts the staking by prohibiting new deposits. Sets staking period to one week. Can be called only by the owner of the contract | function closeDeposit() external onlyOwner {
require(openToDeposit, "Deposit function already closed");
openToDeposit = false;
unlockTime = now + week;
}
| 8,841,942 | [
1,
2083,
716,
2542,
326,
384,
6159,
635,
450,
31597,
310,
394,
443,
917,
1282,
18,
11511,
384,
6159,
3879,
358,
1245,
4860,
18,
4480,
506,
2566,
1338,
635,
326,
3410,
434,
326,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1746,
758,
1724,
1435,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
3190,
774,
758,
1724,
16,
315,
758,
1724,
445,
1818,
4375,
8863,
203,
3639,
1696,
774,
758,
1724,
273,
629,
31,
203,
3639,
7186,
950,
273,
2037,
397,
4860,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x4f800a45631f2c74ef2d37201adf417b3b90ad3c
//Contract name: HormitechToken
//Balance: 0.0499999999999992 Ether
//Verification Date: 1/15/2018
//Transacion Count: 7
// CODE STARTS HERE
pragma solidity ^0.4.13;
contract owned {
/* Owner definition. */
address public owner; // Owner address.
function owned() internal {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner); _;
}
function transferOwnership(address newOwner) onlyOwner public{
owner = newOwner;
}
}
contract token {
/* Base token definition. */
string public name; // Name for the token.
string public symbol; // Symbol for the token.
uint8 public decimals; // Number of decimals of the token.
uint256 public totalSupply; // Total of tokens created.
// Array containing the balance foreach address.
mapping (address => uint256) public balanceOf;
// Array containing foreach address, an array containing each approved address and the amount of tokens it can spend.
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify about a transfer done. */
event Transfer(address indexed from, address indexed to, uint256 value);
/* Initializes the contract */
function token(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) internal {
balanceOf[msg.sender] = initialSupply; // Gives the creator all initial tokens.
totalSupply = initialSupply; // Update total supply.
name = tokenName; // Set the name for display purposes.
symbol = tokenSymbol; // Set the symbol for display purposes.
decimals = decimalUnits; // Amount of decimals for display purposes.
}
/* Internal transfer, only can be called by this contract. */
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0); // Prevent transfer to 0x0 address.
require(balanceOf[_from] > _value); // Check if the sender has enough.
require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows.
balanceOf[_from] -= _value; // Subtract from the sender.
balanceOf[_to] += _value; // Add the same to the recipient.
Transfer(_from, _to, _value); // Notifies the blockchain about the transfer.
}
/// @notice Send `_value` tokens to `_to` from your account.
/// @param _to The address of the recipient.
/// @param _value The amount to send.
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/// @notice Send `_value` tokens to `_to` in behalf of `_from`.
/// @param _from The address of the sender.
/// @param _to The address of the recipient.
/// @param _value The amount to send.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance.
allowance[_from][msg.sender] -= _value; // Updates the allowance array, substracting the amount sent.
_transfer(_from, _to, _value); // Makes the transfer.
return true;
}
/// @notice Allows `_spender` to spend a maximum of `_value` tokens in your behalf.
/// @param _spender The address authorized to spend.
/// @param _value The max amount they can spend.
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value; // Adds a new register to allowance, permiting _spender to use _value of your tokens.
return true;
}
}
contract HormitechToken is owned, token {
/* Specific token definition for -HormitechToken-. */
uint256 public sellPrice = 5000000000000000; // Price applied if someone wants to sell a token.
uint256 public buyPrice = 10000000000000000; // Price applied if someone wants to buy a token.
bool public closeBuy = false; // If true, nobody will be able to buy.
bool public closeSell = false; // If true, nobody will be able to sell.
uint256 public tokensAvailable = balanceOf[this]; // Number of tokens available for sell.
uint256 public solvency = this.balance; // Amount of Ether available to pay sales.
uint256 public profit = 0; // Shows the actual profit for the company.
address public comisionGetter = 0xCd8bf69ad65c5158F0cfAA599bBF90d7f4b52Bb0; // The address that gets the comisions paid.
mapping (address => bool) public frozenAccount; // Array containing foreach address if it's frozen or not.
/* This generates a public event on the blockchain that will notify about an address being freezed. */
event FrozenFunds(address target, bool frozen);
/* This generates a public event on the blockchain that will notify about an addition of Ether to the contract. */
event LogDeposit(address sender, uint amount);
/* This generates a public event on the blockchain that will notify about a Withdrawal of Ether from the contract. */
event LogWithdrawal(address receiver, uint amount);
/* Initializes the contract */
function HormitechToken(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) public token (initialSupply, tokenName, decimalUnits, tokenSymbol) {}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0); // Prevent transfer to 0x0 address.
require(balanceOf[_from] >= _value); // Check if the sender has enough.
require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows.
require(!frozenAccount[_from]); // Check if sender is frozen.
require(!frozenAccount[_to]); // Check if recipient is frozen.
balanceOf[_from] -= _value; // Subtracts _value tokens from the sender.
balanceOf[_to] += _value; // Adds the same amount to the recipient.
_updateTokensAvailable(balanceOf[this]); // Update the balance of tokens available if necessary.
Transfer(_from, _to, _value); // Notifies the blockchain about the transfer.
}
function refillTokens(uint256 _value) public onlyOwner{
// Owner sends tokens to the contract.
_transfer(msg.sender, this, _value);
}
/* Overrides basic transfer function due to comision value */
function transfer(address _to, uint256 _value) public {
// This function requires a comision value of 0.4% of the market value.
uint market_value = _value * sellPrice;
uint comision = market_value * 4 / 1000;
// The token smart-contract pays comision, else the transfer is not possible.
require(this.balance >= comision);
comisionGetter.transfer(comision); // Transfers comision to the comisionGetter.
_transfer(msg.sender, _to, _value);
}
/* Overrides basic transferFrom function due to comision value */
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance.
// This function requires a comision value of 0.4% of the market value.
uint market_value = _value * sellPrice;
uint comision = market_value * 4 / 1000;
// The token smart-contract pays comision, else the transfer is not possible.
require(this.balance >= comision);
comisionGetter.transfer(comision); // Transfers comision to the comisionGetter.
allowance[_from][msg.sender] -= _value; // Updates the allowance array, substracting the amount sent.
_transfer(_from, _to, _value); // Makes the transfer.
return true;
}
/* Internal, updates the balance of tokens available. */
function _updateTokensAvailable(uint256 _tokensAvailable) internal { tokensAvailable = _tokensAvailable; }
/* Internal, updates the balance of Ether available in order to cover potential sales. */
function _updateSolvency(uint256 _solvency) internal { solvency = _solvency; }
/* Internal, updates the profit value */
function _updateProfit(uint256 _increment, bool add) internal{
if (add){
// Increase the profit value
profit = profit + _increment;
}else{
// Decrease the profit value
if(_increment > profit){ profit = 0; }
else{ profit = profit - _increment; }
}
}
/// @notice Create `mintedAmount` tokens and send it to `target`.
/// @param target Address to receive the tokens.
/// @param mintedAmount The amount of tokens target will receive.
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount; // Updates target's balance.
totalSupply += mintedAmount; // Updates totalSupply.
_updateTokensAvailable(balanceOf[this]); // Update the balance of tokens available if necessary.
Transfer(0, this, mintedAmount); // Notifies the blockchain about the tokens created.
Transfer(this, target, mintedAmount); // Notifies the blockchain about the transfer to target.
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens.
/// @param target Address to be frozen.
/// @param freeze Either to freeze target or not.
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze; // Sets the target status. True if it's frozen, False if it's not.
FrozenFunds(target, freeze); // Notifies the blockchain about the change of state.
}
/// @notice Allow addresses to pay `newBuyPrice`ETH when buying and receive `newSellPrice`ETH when selling, foreach token bought/sold.
/// @param newSellPrice Price applied when an address sells its tokens, amount in WEI (1ETH = 10¹⁸WEI).
/// @param newBuyPrice Price applied when an address buys tokens, amount in WEI (1ETH = 10¹⁸WEI).
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice; // Updates the buying price.
buyPrice = newBuyPrice; // Updates the selling price.
}
/// @notice Sets the state of buy and sell operations
/// @param isClosedBuy True if buy operations are closed, False if opened.
/// @param isClosedSell True if sell operations are closed, False if opened.
function setStatus(bool isClosedBuy, bool isClosedSell) onlyOwner public {
closeBuy = isClosedBuy; // Updates the state of buy operations.
closeSell = isClosedSell; // Updates the state of sell operations.
}
/// @notice Deposits Ether to the contract
function deposit() payable public returns(bool success) {
require((this.balance + msg.value) > this.balance); // Checks for overflows.
//Contract has already received the Ether when this function is executed.
_updateSolvency(this.balance); // Updates the solvency value of the contract.
_updateProfit(msg.value, false); // Decrease profit value.
// Decrease because deposits will be done mostly by the owner.
// Possible donations won't count as profit for the company, but in favor of the investors.
LogDeposit(msg.sender, msg.value); // Notifies the blockchain about the Ether received.
return true;
}
/// @notice The owner withdraws Ether from the contract.
/// @param amountInWeis Amount of ETH in WEI which will be withdrawed.
function withdraw(uint amountInWeis) onlyOwner public {
LogWithdrawal(msg.sender, amountInWeis); // Notifies the blockchain about the withdrawal.
_updateSolvency( (this.balance - amountInWeis) ); // Updates the solvency value of the contract.
_updateProfit(amountInWeis, true); // Increase the profit value.
owner.transfer(amountInWeis); // Sends the Ether to owner address.
}
/// @notice Buy tokens from contract by sending Ether.
function buy() public payable {
require(!closeBuy); //Buy operations must be opened
uint amount = msg.value / buyPrice; //Calculates the amount of tokens to be sent
uint market_value = amount * buyPrice; //Market value for this amount
uint comision = market_value * 4 / 1000; //Calculates the comision for this transaction
uint profit_in_transaction = market_value - (amount * sellPrice) - comision; //Calculates the relative profit for this transaction
require(this.balance >= comision); //The token smart-contract pays comision, else the operation is not possible.
comisionGetter.transfer(comision); //Transfers comision to the comisionGetter.
_transfer(this, msg.sender, amount); //Makes the transfer of tokens.
_updateSolvency((this.balance - profit_in_transaction)); //Updates the solvency value of the contract.
_updateProfit(profit_in_transaction, true); //Increase the profit value.
owner.transfer(profit_in_transaction); //Sends profit to the owner of the contract.
}
/// @notice Sell `amount` tokens to the contract.
/// @param amount amount of tokens to be sold.
function sell(uint256 amount) public {
require(!closeSell); //Sell operations must be opened
uint market_value = amount * sellPrice; //Market value for this amount
uint comision = market_value * 4 / 1000; //Calculates the comision for this transaction
uint amount_weis = market_value + comision; //Total in weis that must be paid
require(this.balance >= amount_weis); //Contract must have enough weis
comisionGetter.transfer(comision); //Transfers comision to the comisionGetter
_transfer(msg.sender, this, amount); //Makes the transfer of tokens, the contract receives the tokens.
_updateSolvency( (this.balance - amount_weis) ); //Updates the solvency value of the contract.
msg.sender.transfer(market_value); //Sends Ether to the seller.
}
/// Default function, sender buys tokens by sending ether to the contract:
function () public payable { buy(); }
}
| Specific token definition for -HormitechToken-. */ This generates a public event on the blockchain that will notify about an address being freezed. */ This generates a public event on the blockchain that will notify about an addition of Ether to the contract. */ This generates a public event on the blockchain that will notify about a Withdrawal of Ether from the contract. */ Initializes the contract */ | function HormitechToken(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) public token (initialSupply, tokenName, decimalUnits, tokenSymbol) {}
| 14,099,451 | [
1,
9969,
1147,
2379,
364,
300,
44,
535,
1137,
343,
1345,
17,
18,
342,
1220,
6026,
279,
1071,
871,
603,
326,
16766,
716,
903,
5066,
2973,
392,
1758,
3832,
4843,
94,
329,
18,
342,
1220,
6026,
279,
1071,
871,
603,
326,
16766,
716,
903,
5066,
2973,
392,
2719,
434,
512,
1136,
358,
326,
6835,
18,
342,
1220,
6026,
279,
1071,
871,
603,
326,
16766,
716,
903,
5066,
2973,
279,
3423,
9446,
287,
434,
512,
1136,
628,
326,
6835,
18,
342,
10188,
3128,
326,
6835,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
670,
535,
1137,
343,
1345,
12,
11890,
5034,
2172,
3088,
1283,
16,
533,
1147,
461,
16,
2254,
28,
6970,
7537,
16,
533,
1147,
5335,
13,
1071,
1147,
261,
6769,
3088,
1283,
16,
1147,
461,
16,
6970,
7537,
16,
1147,
5335,
13,
2618,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import {IARTH} from '../IARTH.sol';
import {IARTHPool} from './IARTHPool.sol';
import {IERC20} from '../../ERC20/IERC20.sol';
import {IARTHX} from '../../ARTHX/IARTHX.sol';
import {SafeMath} from '../../utils/math/SafeMath.sol';
import {ArthPoolLibrary} from './ArthPoolLibrary.sol';
import {IARTHController} from '../IARTHController.sol';
import {ISimpleOracle} from '../../Oracle/ISimpleOracle.sol';
import {IERC20Burnable} from '../../ERC20/IERC20Burnable.sol';
import {AccessControl} from '../../access/AccessControl.sol';
import {IUniswapPairOracle} from '../../Oracle/IUniswapPairOracle.sol';
import {RecollateralizeDiscountCurve} from './RecollateralizeDiscountCurve.sol';
/**
* @title ARTHPool.
* @author MahaDAO.
*
* Original code written by:
* - Travis Moore, Jason Huan, Same Kazemian, Sam Sun.
*/
contract ArthPool is AccessControl, IARTHPool {
using SafeMath for uint256;
/**
* @dev Contract instances.
*/
IARTH private _ARTH;
IARTHX private _ARTHX;
IERC20 private _COLLATERAL;
IERC20Burnable private _MAHA;
ISimpleOracle private _ARTHMAHAOracle;
IARTHController private _arthController;
IUniswapPairOracle private _collateralETHOracle;
RecollateralizeDiscountCurve private _recollateralizeDiscountCruve;
bool public mintPaused = false;
bool public redeemPaused = false;
bool public buyBackPaused = false;
bool public recollateralizePaused = false;
bool public override collateralPricePaused = false;
bool public useGlobalCRForMint = true;
bool public useGlobalCRForRedeem = true;
bool public useGlobalCRForRecollateralize = true;
uint256 public mintCollateralRatio;
uint256 public redeemCollateralRatio;
uint256 public recollateralizeCollateralRatio;
uint256 public override buybackFee;
uint256 public override mintingFee;
uint256 public override recollatFee;
uint256 public override redemptionFee;
uint256 public stabilityFee = 1; // In %.
uint256 public buybackCollateralBuffer = 20; // In %.
uint256 public override pausedPrice = 0; // Stores price of the collateral, if price is paused
uint256 public poolCeiling = 0; // Total units of collateral that a pool contract can hold
uint256 public redemptionDelay = 1; // Number of blocks to wait before being able to collect redemption.
uint256 public unclaimedPoolARTHX;
uint256 public unclaimedPoolCollateral;
address public override collateralETHOracleAddress;
mapping(address => uint256) public lastRedeemed;
mapping(address => uint256) public borrowedCollateral;
mapping(address => uint256) public redeemARTHXBalances;
mapping(address => uint256) public redeemCollateralBalances;
bytes32 private constant _RECOLLATERALIZE_PAUSER =
keccak256('RECOLLATERALIZE_PAUSER');
bytes32 private constant _COLLATERAL_PRICE_PAUSER =
keccak256('COLLATERAL_PRICE_PAUSER');
bytes32 private constant _AMO_ROLE = keccak256('AMO_ROLE');
bytes32 private constant _MINT_PAUSER = keccak256('MINT_PAUSER');
bytes32 private constant _REDEEM_PAUSER = keccak256('REDEEM_PAUSER');
bytes32 private constant _BUYBACK_PAUSER = keccak256('BUYBACK_PAUSER');
uint256 private immutable _missingDeciamls;
uint256 private constant _PRICE_PRECISION = 1e6;
uint256 private constant _COLLATERAL_RATIO_MAX = 1e6;
uint256 private constant _COLLATERAL_RATIO_PRECISION = 1e6;
address private _wethAddress;
address private _ownerAddress;
address private _timelockAddress;
address private _collateralAddress;
address private _arthContractAddress;
address private _arthxContractAddress;
/**
* Events.
*/
event Repay(address indexed from, uint256 amount);
event Borrow(address indexed from, uint256 amount);
event StabilityFeesCharged(address indexed from, uint256 fee);
/**
* Modifiers.
*/
modifier onlyByOwnerOrGovernance() {
require(
msg.sender == _timelockAddress || msg.sender == _ownerAddress,
'ArthPool: You are not the owner or the governance timelock'
);
_;
}
modifier onlyAdmin() {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
'ArthPool: You are not the admin'
);
_;
}
modifier onlyAdminOrOwnerOrGovernance() {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()) ||
msg.sender == _timelockAddress ||
msg.sender == _ownerAddress,
'ArthPool: forbidden'
);
_;
}
modifier onlyAMOS {
require(hasRole(_AMO_ROLE, _msgSender()), 'ArthPool: forbidden');
_;
}
modifier notRedeemPaused() {
require(redeemPaused == false, 'ArthPool: Redeeming is paused');
_;
}
modifier notMintPaused() {
require(mintPaused == false, 'ArthPool: Minting is paused');
_;
}
/**
* Constructor.
*/
constructor(
address __arthContractAddress,
address __arthxContractAddress,
address __collateralAddress,
address _creatorAddress,
address __timelockAddress,
address __MAHA,
address __ARTHMAHAOracle,
address __arthController,
uint256 _poolCeiling
) {
_MAHA = IERC20Burnable(__MAHA);
_ARTH = IARTH(__arthContractAddress);
_COLLATERAL = IERC20(__collateralAddress);
_ARTHX = IARTHX(__arthxContractAddress);
_ARTHMAHAOracle = ISimpleOracle(__ARTHMAHAOracle);
_arthController = IARTHController(__arthController);
_ownerAddress = _creatorAddress;
_timelockAddress = __timelockAddress;
_collateralAddress = __collateralAddress;
_arthContractAddress = __arthContractAddress;
_arthxContractAddress = __arthxContractAddress;
poolCeiling = _poolCeiling;
_missingDeciamls = uint256(18).sub(_COLLATERAL.decimals());
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
grantRole(_MINT_PAUSER, _timelockAddress);
grantRole(_REDEEM_PAUSER, _timelockAddress);
grantRole(_BUYBACK_PAUSER, _timelockAddress);
grantRole(_RECOLLATERALIZE_PAUSER, _timelockAddress);
grantRole(_COLLATERAL_PRICE_PAUSER, _timelockAddress);
}
/**
* External.
*/
function setBuyBackCollateralBuffer(uint256 percent)
external
override
onlyAdminOrOwnerOrGovernance
{
require(percent <= 100, 'ArthPool: percent > 100');
buybackCollateralBuffer = percent;
}
function toggleUseGlobalCRForMint(bool flag)
external
override
onlyAdminOrOwnerOrGovernance
{
useGlobalCRForMint = flag;
}
function toggleUseGlobalCRForRedeem(bool flag)
external
override
onlyAdminOrOwnerOrGovernance
{
useGlobalCRForRedeem = flag;
}
function toggleUseGlobalCRForRecollateralize(bool flag)
external
override
onlyAdminOrOwnerOrGovernance
{
useGlobalCRForRecollateralize = flag;
}
function setMintCollateralRatio(uint256 val)
external
override
onlyAdminOrOwnerOrGovernance
{
mintCollateralRatio = val;
}
function setRecollateralizationCurve(RecollateralizeDiscountCurve curve)
external
onlyAdminOrOwnerOrGovernance
{
_recollateralizeDiscountCruve = curve;
}
function setRedeemCollateralRatio(uint256 val)
external
override
onlyAdminOrOwnerOrGovernance
{
redeemCollateralRatio = val;
}
function setRecollateralizeCollateralRatio(uint256 val)
external
override
onlyAdminOrOwnerOrGovernance
{
recollateralizeCollateralRatio = val;
}
function setStabilityFee(uint256 percent)
external
override
onlyAdminOrOwnerOrGovernance
{
require(percent <= 100, 'ArthPool: percent > 100');
stabilityFee = percent;
}
function setCollatETHOracle(
address _collateralWETHOracleAddress,
address __wethAddress
) external override onlyByOwnerOrGovernance {
collateralETHOracleAddress = _collateralWETHOracleAddress;
_collateralETHOracle = IUniswapPairOracle(_collateralWETHOracleAddress);
_wethAddress = __wethAddress;
}
function toggleMinting() external override {
require(hasRole(_MINT_PAUSER, msg.sender));
mintPaused = !mintPaused;
}
function toggleRedeeming() external override {
require(hasRole(_REDEEM_PAUSER, msg.sender));
redeemPaused = !redeemPaused;
}
function toggleRecollateralize() external override {
require(hasRole(_RECOLLATERALIZE_PAUSER, msg.sender));
recollateralizePaused = !recollateralizePaused;
}
function toggleBuyBack() external override {
require(hasRole(_BUYBACK_PAUSER, msg.sender));
buyBackPaused = !buyBackPaused;
}
function toggleCollateralPrice(uint256 newPrice) external override {
require(hasRole(_COLLATERAL_PRICE_PAUSER, msg.sender));
// If pausing, set paused price; else if unpausing, clear pausedPrice.
if (collateralPricePaused == false) pausedPrice = newPrice;
else pausedPrice = 0;
collateralPricePaused = !collateralPricePaused;
}
// Combined into one function due to 24KiB contract memory limit
function setPoolParameters(
uint256 newCeiling,
uint256 newRedemptionDelay,
uint256 newMintFee,
uint256 newRedeemFee,
uint256 newBuybackFee,
uint256 newRecollateralizeFee
) external override onlyByOwnerOrGovernance {
poolCeiling = newCeiling;
redemptionDelay = newRedemptionDelay;
mintingFee = newMintFee;
redemptionFee = newRedeemFee;
buybackFee = newBuybackFee;
recollatFee = newRecollateralizeFee;
}
function setTimelock(address new_timelock)
external
override
onlyByOwnerOrGovernance
{
_timelockAddress = new_timelock;
}
function setOwner(address __ownerAddress)
external
override
onlyByOwnerOrGovernance
{
_ownerAddress = __ownerAddress;
}
function borrow(uint256 _amount) external override onlyAMOS {
require(
_COLLATERAL.balanceOf(address(this)) > _amount,
'ArthPool: Insufficent funds in the pool'
);
_COLLATERAL.transfer(msg.sender, _amount);
borrowedCollateral[msg.sender] += _amount;
emit Borrow(msg.sender, _amount);
}
function repay(uint256 amount) external override onlyAMOS {
require(
borrowedCollateral[msg.sender] > 0,
"ArthPool: Repayer doesn't not have any debt"
);
require(
_COLLATERAL.balanceOf(msg.sender) >= amount,
'ArthPool: balance < required'
);
_COLLATERAL.transferFrom(msg.sender, address(this), amount);
borrowedCollateral[msg.sender] -= amount;
emit Repay(msg.sender, amount);
}
function mint1t1ARTH(uint256 collateralAmount, uint256 arthOutMin)
external
override
notMintPaused
returns (uint256)
{
uint256 collateralAmountD18 = collateralAmount * (10**_missingDeciamls);
//getCRForMint should be grater than 1e6
require(
getCRForMint() >= _COLLATERAL_RATIO_MAX,
'ARHTPool: Collateral ratio < 1'
);
require(
(_COLLATERAL.balanceOf(address(this)))
.sub(unclaimedPoolCollateral)
.add(collateralAmount) <= poolCeiling,
'ARTHPool: ceiling reached'
);
// 1 ARTH for each $1 worth of collateral.
uint256 arthAmountD18 =
ArthPoolLibrary.calcMint1t1ARTH(
getCollateralPrice(),
collateralAmountD18
);
// Remove precision at the end.
arthAmountD18 = (arthAmountD18.mul(uint256(1e6).sub(mintingFee))).div(
1e6
);
require(
arthOutMin <= arthAmountD18,
'ARTHPool: Slippage limit reached'
);
require(
_COLLATERAL.balanceOf(msg.sender) >= collateralAmount,
'ArthPool: balance < required'
);
_COLLATERAL.transferFrom(msg.sender, address(this), collateralAmount);
_ARTH.poolMint(msg.sender, arthAmountD18);
return arthAmountD18;
}
function mintAlgorithmicARTH(uint256 arthxAmountD18, uint256 arthOutMin)
external
override
notMintPaused
returns (uint256)
{
uint256 arthxPrice = _arthController.getARTHXPrice();
require(getCRForMint() == 0, 'ARTHPool: Collateral ratio != 0');
uint256 arthAmountD18 =
ArthPoolLibrary.calcMintAlgorithmicARTH(
arthxPrice, // X ARTHX / 1 USD
arthxAmountD18
);
arthAmountD18 = (arthAmountD18.mul(uint256(1e6).sub(mintingFee))).div(
1e6
);
require(arthOutMin <= arthAmountD18, 'Slippage limit reached');
_ARTH.poolMint(msg.sender, arthAmountD18);
_ARTHX.poolBurnFrom(msg.sender, arthxAmountD18);
return arthAmountD18;
}
// Will fail if fully collateralized or fully algorithmic
// > 0% and < 100% collateral-backed
function mintFractionalARTH(
uint256 collateralAmount,
uint256 arthxAmount,
uint256 arthOutMin
) external override notMintPaused returns (uint256) {
uint256 arthxPrice = _arthController.getARTHXPrice();
uint256 collateralRatioForMint = getCRForMint();
require(
collateralRatioForMint < _COLLATERAL_RATIO_MAX &&
collateralRatioForMint > 0,
'ARTHPool: fails (.000001 <= Collateral ratio <= .999999)'
);
require(
_COLLATERAL
.balanceOf(address(this))
.sub(unclaimedPoolCollateral)
.add(collateralAmount) <= poolCeiling,
'ARTHPool: ceiling reached.'
);
uint256 collateralAmountD18 = collateralAmount * (10**_missingDeciamls);
ArthPoolLibrary.MintFAParams memory inputParams =
ArthPoolLibrary.MintFAParams(
arthxPrice,
getCollateralPrice(),
arthxAmount,
collateralAmountD18,
collateralRatioForMint
);
(uint256 mintAmount, uint256 arthxNeeded) =
ArthPoolLibrary.calcMintFractionalARTH(inputParams);
mintAmount = (mintAmount.mul(uint256(1e6).sub(mintingFee))).div(1e6);
require(arthOutMin <= mintAmount, 'ARTHPool: Slippage limit reached');
require(arthxNeeded <= arthxAmount, 'ARTHPool: ARTHX < required');
_ARTHX.poolBurnFrom(msg.sender, arthxNeeded);
require(
_COLLATERAL.balanceOf(msg.sender) >= collateralAmount,
'ArthPool: balance < require'
);
_COLLATERAL.transferFrom(msg.sender, address(this), collateralAmount);
_ARTH.poolMint(address(this), mintAmount);
return mintAmount;
}
// Redeem collateral. 100% collateral-backed
function redeem1t1ARTH(uint256 arthAmount, uint256 collateralOutMin)
external
override
notRedeemPaused
{
require(
getCRForRedeem() == _COLLATERAL_RATIO_MAX,
'Collateral ratio must be == 1'
);
// Need to adjust for decimals of collateral
uint256 arthAmountPrecision = arthAmount.div(10**_missingDeciamls);
uint256 collateralNeeded =
ArthPoolLibrary.calcRedeem1t1ARTH(
getCollateralPrice(),
arthAmountPrecision
);
collateralNeeded = (
collateralNeeded.mul(uint256(1e6).sub(redemptionFee))
)
.div(1e6);
require(
collateralNeeded <=
_COLLATERAL.balanceOf(address(this)).sub(
unclaimedPoolCollateral
),
'ARTHPool: Not enough collateral in pool'
);
require(
collateralOutMin <= collateralNeeded,
'ARTHPool: Slippage limit reached'
);
redeemCollateralBalances[msg.sender] = redeemCollateralBalances[
msg.sender
]
.add(collateralNeeded);
unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateralNeeded);
lastRedeemed[msg.sender] = block.number;
_chargeStabilityFee(arthAmount);
// Move all external functions to the end
_ARTH.poolBurnFrom(msg.sender, arthAmount);
}
// Will fail if fully collateralized or algorithmic
// Redeem ARTH for collateral and ARTHX. > 0% and < 100% collateral-backed
function redeemFractionalARTH(
uint256 arthAmount,
uint256 arthxOutMin,
uint256 collateralOutMin
) external override notRedeemPaused {
uint256 arthxPrice = _arthController.getARTHXPrice();
uint256 collateralRatioForRedeem = getCRForRedeem();
require(
collateralRatioForRedeem < _COLLATERAL_RATIO_MAX &&
collateralRatioForRedeem > 0,
'ARTHPool: Collateral ratio needs to be between .000001 and .999999'
);
uint256 collateralPriceGMU = getCollateralPrice();
uint256 arthAmountPostFee =
(arthAmount.mul(uint256(1e6).sub(redemptionFee))).div(
_PRICE_PRECISION
);
uint256 arthxGMUValueD18 =
arthAmountPostFee.sub(
arthAmountPostFee.mul(collateralRatioForRedeem).div(
_PRICE_PRECISION
)
);
uint256 arthxAmount =
arthxGMUValueD18.mul(_PRICE_PRECISION).div(arthxPrice);
// Need to adjust for decimals of collateral
uint256 arthAmountPrecision =
arthAmountPostFee.div(10**_missingDeciamls);
uint256 collateralDollatValue =
arthAmountPrecision.mul(collateralRatioForRedeem).div(
_PRICE_PRECISION
);
uint256 collateralAmount =
collateralDollatValue.mul(_PRICE_PRECISION).div(collateralPriceGMU);
require(
collateralAmount <=
_COLLATERAL.balanceOf(address(this)).sub(
unclaimedPoolCollateral
),
'Not enough collateral in pool'
);
require(
collateralOutMin <= collateralAmount,
'Slippage limit reached [collateral]'
);
require(arthxOutMin <= arthxAmount, 'Slippage limit reached [ARTHX]');
redeemCollateralBalances[msg.sender] += collateralAmount;
unclaimedPoolCollateral += collateralAmount;
redeemARTHXBalances[msg.sender] += arthxAmount;
unclaimedPoolARTHX += arthxAmount;
lastRedeemed[msg.sender] = block.number;
_chargeStabilityFee(arthAmount);
// Move all external functions to the end
_ARTH.poolBurnFrom(msg.sender, arthAmount);
_ARTHX.poolMint(address(this), arthxAmount);
}
// Redeem ARTH for ARTHX. 0% collateral-backed
function redeemAlgorithmicARTH(uint256 arthAmount, uint256 arthxOutMin)
external
override
notRedeemPaused
{
uint256 arthxPrice = _arthController.getARTHXPrice();
uint256 collateralRatioForRedeem = getCRForRedeem();
require(collateralRatioForRedeem == 0, 'Collateral ratio must be 0');
uint256 arthxGMUValueD18 = arthAmount;
arthxGMUValueD18 = (
arthxGMUValueD18.mul(uint256(1e6).sub(redemptionFee))
)
.div(_PRICE_PRECISION); // apply fees
uint256 arthxAmount =
arthxGMUValueD18.mul(_PRICE_PRECISION).div(arthxPrice);
redeemARTHXBalances[msg.sender] = redeemARTHXBalances[msg.sender].add(
arthxAmount
);
unclaimedPoolARTHX += arthxAmount;
lastRedeemed[msg.sender] = block.number;
require(arthxOutMin <= arthxAmount, 'Slippage limit reached');
_chargeStabilityFee(arthAmount);
// Move all external functions to the end
_ARTH.poolBurnFrom(msg.sender, arthAmount);
_ARTHX.poolMint(address(this), arthxAmount);
}
// After a redemption happens, transfer the newly minted ARTHX and owed collateral from this pool
// contract to the user. Redemption is split into two functions to prevent flash loans from being able
// to take out ARTH/collateral from the system, use an AMM to trade the new price, and then mint back into the system.
function collectRedemption() external override {
require(
(lastRedeemed[msg.sender].add(redemptionDelay)) <= block.number,
'Must wait for redemptionDelay blocks before collecting redemption'
);
uint256 ARTHXAmount;
uint256 CollateralAmount;
bool sendARTHX = false;
bool sendCollateral = false;
// Use Checks-Effects-Interactions pattern
if (redeemARTHXBalances[msg.sender] > 0) {
ARTHXAmount = redeemARTHXBalances[msg.sender];
redeemARTHXBalances[msg.sender] = 0;
unclaimedPoolARTHX = unclaimedPoolARTHX.sub(ARTHXAmount);
sendARTHX = true;
}
if (redeemCollateralBalances[msg.sender] > 0) {
CollateralAmount = redeemCollateralBalances[msg.sender];
redeemCollateralBalances[msg.sender] = 0;
unclaimedPoolCollateral = unclaimedPoolCollateral.sub(
CollateralAmount
);
sendCollateral = true;
}
if (sendARTHX == true) _ARTHX.transfer(msg.sender, ARTHXAmount);
if (sendCollateral == true)
_COLLATERAL.transfer(msg.sender, CollateralAmount);
}
// When the protocol is recollateralizing, we need to give a discount of ARTHX to hit the new CR target
// Thus, if the target collateral ratio is higher than the actual value of collateral, minters get ARTHX for adding collateral
// This function simply rewards anyone that sends collateral to a pool with the same amount of ARTHX + the bonus rate
// Anyone can call this function to recollateralize the protocol and take the extra ARTHX value from the bonus rate as an arb opportunity
function recollateralizeARTH(uint256 collateralAmount, uint256 arthxOutMin)
external
override
returns (uint256)
{
require(recollateralizePaused == false, 'Recollateralize is paused');
uint256 collateralAmountD18 = collateralAmount * (10**_missingDeciamls);
uint256 arthxPrice = _arthController.getARTHXPrice();
uint256 arthTotalSupply = _ARTH.totalSupply();
uint256 collateralRatioForRecollateralize = getCRForRecollateralize();
uint256 globalCollatValue = _arthController.getGlobalCollateralValue();
(uint256 collateralUnits, uint256 amountToRecollateralize) =
ArthPoolLibrary.calcRecollateralizeARTHInner(
collateralAmountD18,
getCollateralPrice(),
globalCollatValue,
arthTotalSupply,
collateralRatioForRecollateralize
);
uint256 collateralUnitsPrecision =
collateralUnits.div(10**_missingDeciamls);
// NEED to make sure that recollatFee is less than 1e6.
uint256 arthxPaidBack =
amountToRecollateralize
.mul(
uint256(1e6)
.add(_recollateralizeDiscountCruve.getCurvedDiscount())
.sub(recollatFee)
)
.div(arthxPrice);
require(arthxOutMin <= arthxPaidBack, 'Slippage limit reached');
require(
_COLLATERAL.balanceOf(msg.sender) >= collateralUnitsPrecision,
'ArthPool: balance < required'
);
_COLLATERAL.transferFrom(
msg.sender,
address(this),
collateralUnitsPrecision
);
_ARTHX.poolMint(msg.sender, arthxPaidBack);
return arthxPaidBack;
}
// Function can be called by an ARTHX holder to have the protocol buy back ARTHX with excess collateral value from a desired collateral pool
// This can also happen if the collateral ratio > 1
function buyBackARTHX(uint256 arthxAmount, uint256 collateralOutMin)
external
override
{
require(buyBackPaused == false, 'Buyback is paused');
uint256 arthxPrice = _arthController.getARTHXPrice();
ArthPoolLibrary.BuybackARTHXParams memory inputParams =
ArthPoolLibrary.BuybackARTHXParams(
getAvailableExcessCollateralDV(),
arthxPrice,
getCollateralPrice(),
arthxAmount
);
uint256 collateralEquivalentD18 =
(ArthPoolLibrary.calcBuyBackARTHX(inputParams))
.mul(uint256(1e6).sub(buybackFee))
.div(1e6);
uint256 collateralPrecision =
collateralEquivalentD18.div(10**_missingDeciamls);
require(
collateralOutMin <= collateralPrecision,
'Slippage limit reached'
);
// Give the sender their desired collateral and burn the ARTHX
_ARTHX.poolBurnFrom(msg.sender, arthxAmount);
_COLLATERAL.transfer(msg.sender, collateralPrecision);
}
function getARTHMAHAPrice() public view override returns (uint256) {
return _ARTHMAHAOracle.getPrice();
}
function getGlobalCR() public view override returns (uint256) {
return _arthController.getGlobalCollateralRatio();
}
function getCRForMint() public view override returns (uint256) {
if (useGlobalCRForMint) return getGlobalCR();
return mintCollateralRatio;
}
function getCRForRedeem() public view override returns (uint256) {
if (useGlobalCRForRedeem) return getGlobalCR();
return redeemCollateralRatio;
}
function getCRForRecollateralize() public view override returns (uint256) {
if (useGlobalCRForRecollateralize) return getGlobalCR();
return recollateralizeCollateralRatio;
}
function getCollateralGMUBalance() public view override returns (uint256) {
if (collateralPricePaused) {
return
(
_COLLATERAL.balanceOf(address(this)).sub(
unclaimedPoolCollateral
)
)
.mul(10**_missingDeciamls)
.mul(pausedPrice)
.div(_PRICE_PRECISION);
}
uint256 ethGMUPrice = _arthController.getETHGMUPrice();
uint256 ethCollateralPrice =
_collateralETHOracle.consult(
_wethAddress,
_PRICE_PRECISION * (10**_missingDeciamls)
);
uint256 collateralGMUPrice =
ethGMUPrice.mul(_PRICE_PRECISION).div(ethCollateralPrice);
return
(_COLLATERAL.balanceOf(address(this)).sub(unclaimedPoolCollateral))
.mul(10**_missingDeciamls)
.mul(collateralGMUPrice)
.div(_PRICE_PRECISION);
}
// Returns the value of excess collateral held in this Arth pool, compared to what is
// needed to maintain the global collateral ratio
function getAvailableExcessCollateralDV()
public
view
override
returns (uint256)
{
uint256 totalSupply = _ARTH.totalSupply();
uint256 globalCollateralRatio = getGlobalCR();
uint256 globalCollatValue = _arthController.getGlobalCollateralValue();
// Check if overcollateralized contract with CR > 1.
if (globalCollateralRatio > _COLLATERAL_RATIO_PRECISION)
globalCollateralRatio = _COLLATERAL_RATIO_PRECISION;
// Calculates collateral needed to back each 1 ARTH with $1 of collateral at current CR.
uint256 reqCollateralGMUValue =
(totalSupply.mul(globalCollateralRatio)).div(
_COLLATERAL_RATIO_PRECISION
);
// TODO: add a 10-20% buffer for volatile collaterals.
if (globalCollatValue > reqCollateralGMUValue) {
uint256 excessCollateral =
globalCollatValue.sub(reqCollateralGMUValue);
uint256 bufferValue =
excessCollateral.mul(buybackCollateralBuffer).div(100);
return excessCollateral.sub(bufferValue);
}
return 0;
}
function getCollateralPrice() public view override returns (uint256) {
if (collateralPricePaused) return pausedPrice;
uint256 ethGMUPrice = _arthController.getETHGMUPrice();
return
ethGMUPrice.mul(_PRICE_PRECISION).div(
_collateralETHOracle.consult(
_wethAddress,
_PRICE_PRECISION * (10**_missingDeciamls)
)
);
}
function estimateStabilityFeeInMAHA(uint256 amount)
public
view
returns (uint256)
{
uint256 stabilityFeeInARTH = amount.mul(stabilityFee).div(100);
return getARTHMAHAPrice().mul(stabilityFeeInARTH).div(1e18); // NOTE: this is might change asper ARTH's decimals and price precision.
}
/**
* Internal.
*/
function _chargeStabilityFee(uint256 amount) internal {
require(amount > 0, 'ArthPool: amount = 0');
if (stabilityFee > 0) {
uint256 stabilityFeeInMAHA = estimateStabilityFeeInMAHA(amount);
_MAHA.burnFrom(msg.sender, stabilityFeeInMAHA);
emit StabilityFeesCharged(msg.sender, stabilityFeeInMAHA);
}
return;
}
}
| If pausing, set paused price; else if unpausing, clear pausedPrice. | function toggleCollateralPrice(uint256 newPrice) external override {
require(hasRole(_COLLATERAL_PRICE_PAUSER, msg.sender));
if (collateralPricePaused == false) pausedPrice = newPrice;
else pausedPrice = 0;
collateralPricePaused = !collateralPricePaused;
}
| 927,558 | [
1,
2047,
6790,
9940,
16,
444,
17781,
6205,
31,
469,
309,
640,
8774,
9940,
16,
2424,
17781,
5147,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
10486,
13535,
2045,
287,
5147,
12,
11890,
5034,
394,
5147,
13,
3903,
3849,
288,
203,
3639,
2583,
12,
5332,
2996,
24899,
4935,
12190,
654,
1013,
67,
7698,
1441,
67,
4066,
4714,
16,
1234,
18,
15330,
10019,
203,
203,
3639,
309,
261,
12910,
2045,
287,
5147,
28590,
422,
629,
13,
17781,
5147,
273,
394,
5147,
31,
203,
3639,
469,
17781,
5147,
273,
374,
31,
203,
203,
3639,
4508,
2045,
287,
5147,
28590,
273,
401,
12910,
2045,
287,
5147,
28590,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.5.8 <0.7.0;
contract Admin {
address adminAddress;
constructor () internal {
}
function isAdmin () public view returns (bool) {
return adminAddress == msg.sender;
}
modifier admin {
//require (isAdmin(), "user is not admin");
require (adminAddress == msg.sender, "user is not admin");
_;
}
}
contract Site is Admin {
struct Artist {
string name;
string description;
bool enabled;
// address payable addr;
}
struct Feature {
uint startTime;
uint endTime;
int64 lastFeatureId; // -1 if none
int64 currentBidId; // -1 if none
bool accepted; // artist has approved the top bid for this feature
}
struct Art {
// uint32 id;
//uint16 artistId;
address artistAddress;
bool finished;
int64 currentFeatureId; // -1 if none
}
struct Bid {
// uint32 id;
int64 lowerBidId; // if this outbids an older bid, otherwise -1
address payable addr;
uint amount;
string request;
}
// Artist[] artists;
mapping (address => Artist) artists;
address[] artistAddresses;
Art[] art;
Feature[] features;
Bid[] bids;
uint64 fee;
string testMessage;
event FeatureCreated (uint64 featureId);
event ArtCreated (uint64 artId);
// limit to admin
function setFee (uint64 _fee) public {
fee = _fee;
}
function getFee () public view returns (uint64) {
return fee;
}
function isArtist () public view returns (bool) {
return artists[msg.sender].enabled;
}
// probably isn't useful. We want to know if msg.sender matches specific artist generally
modifier artist {
// require (isArtist(), "user is not an artist"); // does not work
require (artists[msg.sender].enabled, "user is not an artist");
_;
}
// change when struct definition changes
function getArt (uint i) public view returns (address, bool, int64) {
return (art[i].artistAddress, art[i].finished, art[i].currentFeatureId);
}
function getNumArt () public view returns (uint) {
return art.length;
}
function getNumArtist () public view returns (uint) {
return artistAddresses.length;
}
function getArtist (address artistAddress) public view returns (string memory, string memory, address payable) {
Artist memory a = artists[artistAddress];
address payable p = address(uint160(artistAddress));
return (a.name, a.description, p);
}
function getDisplayFeature (uint16 artId) public view returns (int64) {
Art memory thisArt = art[artId];
int64 latestFeature = thisArt.currentFeatureId;
if (latestFeature > -1) {
if (thisArt.finished) {
return latestFeature;
} else {
return features[uint(latestFeature)].lastFeatureId;
}
} else {
return -1;
}
}
function getFeature (uint64 featureId) public view returns (uint, uint, int64, int64, bool) {
Feature memory f = features[uint(featureId)];
return (f.startTime,f.endTime,f.lastFeatureId,f.currentBidId,f.accepted);
}
//TODO add admin back when fixed
function addArtist (address payable _addr) public {
// require (adminAddress == msg.sender, "user is not admin");
bool _isAdmin = adminAddress == msg.sender;
artists[_addr] = Artist("", "", true);
artistAddresses.push(_addr);
}
function modifyArtistProfile (string memory _name, string memory _description) public {
Artist storage artist = artists[msg.sender];
artist.name = _name;
artist.description = _description;
}
//TODO add back artist modifier when fixed
function startArt () public {
bool isArtistA = isArtist();
bool isArtistB = artists[msg.sender].enabled;
art.push(Art(msg.sender, false, -1));
}
//TODO add back artist modifier when fixed
function startFeature (uint64 artId, uint _endTime) public {
Art storage thisArt = art[artId];
//require (thisArt.artistAddress == msg.sender, "can't start a feature for art you don't own!");
Feature memory thisFeature = Feature (now, _endTime, thisArt.currentFeatureId, -1, false);
features.push(thisFeature);
thisArt.currentFeatureId = int64(features.length - 1);
}
// starts art with an initial feature already filled in by the artist
function startArtWithFeature () public {
Feature memory startFeature = Feature (now, now, -1, -1, true);
features.push(startFeature);
int64 featureId = int64(features.length - 1);
emit FeatureCreated(uint64(featureId));
art.push(Art(msg.sender, false, featureId));
emit ArtCreated(uint64(art.length - 1));
}
function getBid (uint64 bidId) public view returns (int64, address payable, uint, string memory) {
Bid memory b = bids[bidId];
return (b.lowerBidId, b.addr, b.amount, b.request);
}
// TODO make sure you can't bid on feature auctions that have ended
function makeBid (uint64 artId, string memory _request) public payable returns (bool, string memory) {
Art memory thisArt = art[artId];
uint actualBid = msg.value - fee;
if (thisArt.currentFeatureId > -1) {
Feature storage thisFeature = features[uint(thisArt.currentFeatureId)];
if (thisFeature.currentBidId > -1) {
Bid memory oldBid = bids[uint(thisFeature.currentBidId)];
if (actualBid > oldBid.amount) {
Bid memory newBid = Bid (thisFeature.currentBidId, msg.sender, actualBid, _request);
bids.push(newBid);
thisFeature.currentBidId = int64(bids.length - 1);
return (true, "You're now the top bidder!");
} else { // insufficient bid
return (false, "Your bid must be higher than the current maximum bid");
}
} else { // very first bid
Bid memory newBid = Bid (-1, msg.sender, actualBid, _request);
bids.push(newBid);
thisFeature.currentBidId = int64(bids.length - 1);
return (true, "You've made the very first bid!");
}
} else {
return (false, "This art isn't open for bidding yet");
}
}
// TODO make function for artist to cancel bid if they hate the request
// TODO make this callable only by artist who owns artwork?
function endBidding (uint64 artId) public {
Art memory thisArt = art[artId];
// require (thisArt.currentFeatureId > -1, "can't end bidding when there is no current feature");
Feature storage thisFeature = features[uint(thisArt.currentFeatureId)];
// require (now > thisFeature.endTime, "Can't end auction prematurely");
if (thisFeature.currentBidId > -1) {
Bid memory winningBid = bids[uint(thisFeature.currentBidId)];
if (winningBid.lowerBidId > -1) {
// refund losing bids
Bid memory currentBid = winningBid; // assignment should be overwritten immediately
for (currentBid = bids[uint(winningBid.lowerBidId)]; currentBid.lowerBidId != -1; currentBid = bids[uint(currentBid.lowerBidId)]) {
currentBid.addr.transfer(currentBid.amount);
}
currentBid.addr.transfer(currentBid.amount); // need one last call for last bid
}
address payable aa = address(uint160(thisArt.artistAddress));
aa.transfer(winningBid.amount);
} else { // there are no bids!
}
thisFeature.accepted = true;
}
function nextFeature (uint64 artId, uint endTime) public {
endBidding(artId);
startFeature(artId, endTime);
}
function getTestMessage() public view returns (string memory) {
return testMessage;
}
constructor (address _admin) public {
adminAddress =_admin;
testMessage = "A test has passed";
}
function finishArt (uint64 artId) public {
endBidding(artId);
Art storage thisArt = art[artId];
thisArt.finished = true;
}
}
| TODO make sure you can't bid on feature auctions that have ended | function makeBid (uint64 artId, string memory _request) public payable returns (bool, string memory) {
Art memory thisArt = art[artId];
uint actualBid = msg.value - fee;
if (thisArt.currentFeatureId > -1) {
Feature storage thisFeature = features[uint(thisArt.currentFeatureId)];
if (thisFeature.currentBidId > -1) {
Bid memory oldBid = bids[uint(thisFeature.currentBidId)];
if (actualBid > oldBid.amount) {
Bid memory newBid = Bid (thisFeature.currentBidId, msg.sender, actualBid, _request);
bids.push(newBid);
thisFeature.currentBidId = int64(bids.length - 1);
return (true, "You're now the top bidder!");
return (false, "Your bid must be higher than the current maximum bid");
}
Bid memory newBid = Bid (-1, msg.sender, actualBid, _request);
bids.push(newBid);
thisFeature.currentBidId = int64(bids.length - 1);
return (true, "You've made the very first bid!");
}
return (false, "This art isn't open for bidding yet");
}
}
| 15,794,599 | [
1,
6241,
1221,
3071,
1846,
848,
1404,
9949,
603,
2572,
279,
4062,
87,
716,
1240,
16926,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
1221,
17763,
261,
11890,
1105,
3688,
548,
16,
533,
3778,
389,
2293,
13,
1071,
8843,
429,
1135,
261,
6430,
16,
533,
3778,
13,
288,
203,
565,
9042,
3778,
333,
4411,
273,
3688,
63,
485,
548,
15533,
203,
565,
2254,
3214,
17763,
273,
1234,
18,
1132,
300,
14036,
31,
203,
565,
309,
261,
2211,
4411,
18,
2972,
4595,
548,
405,
300,
21,
13,
288,
203,
1377,
7881,
2502,
333,
4595,
273,
4467,
63,
11890,
12,
2211,
4411,
18,
2972,
4595,
548,
13,
15533,
203,
203,
1377,
309,
261,
2211,
4595,
18,
2972,
17763,
548,
405,
300,
21,
13,
288,
203,
3639,
605,
350,
3778,
1592,
17763,
273,
30534,
63,
11890,
12,
2211,
4595,
18,
2972,
17763,
548,
13,
15533,
203,
203,
3639,
309,
261,
18672,
17763,
405,
1592,
17763,
18,
8949,
13,
288,
203,
1850,
605,
350,
3778,
394,
17763,
273,
605,
350,
261,
2211,
4595,
18,
2972,
17763,
548,
16,
1234,
18,
15330,
16,
3214,
17763,
16,
389,
2293,
1769,
203,
1850,
30534,
18,
6206,
12,
2704,
17763,
1769,
203,
1850,
333,
4595,
18,
2972,
17763,
548,
273,
509,
1105,
12,
70,
2232,
18,
2469,
300,
404,
1769,
203,
1850,
327,
261,
3767,
16,
315,
6225,
4565,
2037,
326,
1760,
9949,
765,
4442,
1769,
203,
203,
1850,
327,
261,
5743,
16,
315,
15446,
9949,
1297,
506,
10478,
2353,
326,
783,
4207,
9949,
8863,
203,
3639,
289,
203,
203,
3639,
605,
350,
3778,
394,
17763,
273,
605,
350,
24927,
21,
16,
1234,
18,
15330,
16,
3214,
17763,
16,
389,
2293,
1769,
203,
3639,
2
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-31
*/
// 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/security/Pausable.sol
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File: @openzeppelin/contracts/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 v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (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: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _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));
}
return super.tokenURI(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), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @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 override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Pausable.sol)
pragma solidity ^0.8.0;
/**
* @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 ERC721Pausable is ERC721, Pausable {
/**
* @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");
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// File: contracts/ERC721Full.sol
/*
*
* https://www.yomobile.com/ offers this Ethereum Mainnet NFT collection
* smart contract to allow YO MOBILE NFT owners export their NFTs for sale
* on any NFT auction platform they choose.
*
*/
pragma solidity 0.8.13;
/**
* @title Yo Mobile Mainnet ERC721 contract to export NFTs to the outside world.
* @author Horizon Globex GmbH
*/
contract ERC721Full is ERC721, Ownable, ERC721Burnable, ERC721Enumerable, ERC721Pausable, ERC721URIStorage {
/**
* @notice Set the token base for all tokens. Can be overridden with setOverrideURI.
*
* @param name The name of the token.
* @param symbol The short symbol for this token.
*/
constructor(string memory name, string memory symbol) ERC721(name, symbol) {
tokenBase = "https://yomobile-nft-lookup.azurewebsites.net/api/nftlookup/";
}
/**
* @dev When exporting from YO MOBILE to Mainnet the token is put out of reach on YO MOBILE
* and "moved" here.
* Called with a sequential tokenId number (1, 2, 3 etc.)
*
* @param to The wallet to allocate the token to.
* @param tokenId The unique id of the NFT.
*/
function mint(address to, uint256 tokenId) public virtual onlyOwner {
_mint(to, tokenId);
}
/**
* @notice Ensure base class is called.
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @notice Override to call the URI Storage version to remove any entries.
*/
function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) {
ERC721URIStorage._burn(tokenId);
}
/**
* @notice Call the Enumerable version so all supported interfaces are returned as such.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return ERC721Enumerable.supportsInterface(interfaceId);
}
/**
* @notice Get the URI of the specified NFT id.
*
* @dev See {IERC721URIStorage-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
return ERC721URIStorage.tokenURI(tokenId);
}
/**
* @notice Allow the base of the tokenURI to be updated at a later date.
*/
string public tokenBase;
/**
* @notice Allow the owner to change the tokenURI for all tokens.
*
* @param base The new start of the tokenURI to the JSON files.
*/
function setTokenBase(string memory base) public onlyOwner {
tokenBase = base;
}
/**
* @notice The location of the token JSON files.
*/
function _baseURI() internal view virtual override returns (string memory) {
return tokenBase;
}
} | * @dev When exporting from YO MOBILE to Mainnet the token is put out of reach on YO MOBILE and "moved" here. Called with a sequential tokenId number (1, 2, 3 etc.) @param to The wallet to allocate the token to. @param tokenId The unique id of the NFT./ | function mint(address to, uint256 tokenId) public virtual onlyOwner {
_mint(to, tokenId);
}
| 6,748,680 | [
1,
9434,
3359,
310,
628,
1624,
51,
490,
29826,
358,
12740,
2758,
326,
1147,
353,
1378,
596,
434,
9287,
603,
1624,
51,
490,
29826,
471,
315,
81,
9952,
6,
2674,
18,
11782,
598,
279,
21210,
1147,
548,
1300,
261,
21,
16,
576,
16,
890,
5527,
12998,
225,
358,
1021,
9230,
358,
10101,
326,
1147,
358,
18,
225,
1147,
548,
1021,
3089,
612,
434,
326,
423,
4464,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
312,
474,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
1071,
5024,
1338,
5541,
288,
203,
3639,
389,
81,
474,
12,
869,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.0;
/* AmpleForthGold AAU Midas Distributor.
**
** (c) 2020. Developed by the AmpleForthGold Team.
**
** www.ampleforth.gold
*/
//import "openzeppelin-solidity/contracts/math/SafeMath.sol";
//pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
//import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
//pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
//pragma solidity ^0.5.0;
//import "../GSN/Context.sol";
//pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @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 {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
//import "./TokenPool.sol";
//pragma solidity 0.5.0;
//import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
//import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
/**
* @title A simple holder of tokens.
* This is a simple contract to hold tokens. It's useful in the case where a separate contract
* needs to hold multiple distinct pools of the same token.
*/
contract TokenPool is Ownable {
IERC20 public token;
constructor(IERC20 _token) public {
token = _token;
}
function balance() public view returns (uint256) {
return token.balanceOf(address(this));
}
function transfer(address to, uint256 value)
external
onlyOwner
returns (bool)
{
return token.transfer(to, value);
}
}
/**
* @title Midas Distributor
* @dev A smart-contract based mechanism to distribute tokens over time, inspired loosely by
* Compound, Uniswap and Ampleforth.
*
* The ampleforth geyser has the concept of a 'locked pool' in the geyser. MidasDistributor
* performs a similar action to the ampleforth geyser locked pool but allows for multiple
* geysers (which we call MidasAgents).
*
* Distribution tokens are added to a pool in the contract and, over time, are sent to
* multiple midas agents based on a distribution share. Each agent gets a set
* percentage of the pool each time a distribution occurs.
*
* Before unstaking the tokens in an agent it would be benifical to maximise the
* take: to perform a distribution. That distribution event would be at the stakholders
* expense, and we allow anyone to perform a distribution.
*
* Multiple midas agents can be registered, deregistered and have their distribution
* percentage adjusted. The distributor must be locked for adjustments to be made.
*
* More background and motivation available at the AmpleForthGold github & website.
*/
contract MidasDistributor is Ownable {
using SafeMath for uint256;
event TokensLocked(uint256 amount, uint256 total);
event TokensDistributed(uint256 amount, uint256 total);
/* the ERC20 token to distribute */
IERC20 public token;
/* timestamp of last distribution event. */
uint256 public lastDistributionTimestamp;
/* When *true* the distributor:
* 1) shall distribute tokens to agents,
* 2) shall not allow for the registration or
* modification of agent details.
* When *false* the distributor:
* 1) shall not distribute tokens to agents,
* 2) shall allow for the registration and
* modification of agent details.
*/
bool public distributing = false;
/* Allows us to represent a number by moving the decimal point. */
uint256 public constant DECIMALS_EXP = 10**12;
/* Represents the distribution rate per second.
* Distribution rate is (0.5% per day) == (5.78703e-8 per second).
*/
uint256 public constant PER_SECOND_INTEREST
= (DECIMALS_EXP * 5) / (1000 * 1 days);
/* The collection of Agents and their percentage share. */
struct MidasAgent {
/* reference to a Midas Agent (destination for distributions) */
address agent;
/* Share of the distribution as a percentage.
* i.e. 14% == 14
* The sum of all shares must be equal to 100.
*/
uint8 share;
}
MidasAgent[] public agents;
/**
* @param _distributionToken The token to be distributed.
*/
constructor(IERC20 _distributionToken) public {
token = _distributionToken;
lastDistributionTimestamp = block.timestamp;
}
/**
* @notice Sets the distributing state of the contract
* @param _distributing the distributing state.
*/
function setDistributionState(bool _distributing) external onlyOwner {
/* we can only become enabled if the sum of shares == 100%. */
if (_distributing == true) {
require(checkAgentPercentage() == true);
}
distributing = _distributing;
}
/**
* @notice Adds an Agent
* @param _agent Address of the destination agent
* @param _share Percentage share of distribution (can be 0)
*/
function addAgent(address _agent, uint8 _share) external onlyOwner {
require(_share <= uint8(100));
distributing = false;
agents.push(MidasAgent({agent: _agent, share: _share}));
}
/**
* @notice Removes an Agent
* @param _index Index of Agent to remove.
* Agent ordering may have changed since adding.
*/
function removeAgent(uint256 _index) external onlyOwner {
require(_index < agents.length, "index out of bounds");
distributing = false;
if (_index < agents.length - 1) {
agents[_index] = agents[agents.length - 1];
}
agents.length--;
}
/**
* @notice Sets an Agents share of the distribution.
* @param _index Index of Agents. Ordering may have changed since adding.
* @param _share Percentage share of the distribution (can be 0).
*/
function setAgentShare(uint256 _index, uint8 _share) external onlyOwner {
require(
_index < agents.length,
"index must be in range of stored tx list"
);
require(_share <= uint8(100));
distributing = false;
agents[_index].share = _share;
}
/**
* @return Number of midas agents in agents list.
*/
function agentsSize() public view returns (uint256) {
return agents.length;
}
/**
* @return boolean true if the percentage of all
* agents equals 100%. */
function checkAgentPercentage() public view returns (bool) {
uint256 sum = 0;
for (uint256 i = 0; i < agents.length; i++) {
sum += agents[i].share;
}
return (uint256(100) == sum);
}
/**
* @return gets the total balance of the distributor
*/
function balance() public view returns (uint256) {
return token.balanceOf(address(this));
}
function getElapsedTime() public view returns(uint256) {
/* Checking for a wormhole or time dialation event.
* this error may also be caused by sunspots. */
require(block.timestamp >= lastDistributionTimestamp);
return (block.timestamp - lastDistributionTimestamp);
}
/* Gets the (total) amount that would be distributed
* if a distribution event happened now. */
function getDistributionAmount() public view returns (uint256) {
return
balance()
.mul(getElapsedTime())
.mul(PER_SECOND_INTEREST)
.div(DECIMALS_EXP);
}
/* Gets the amount that would be distributed to a specific agent
* if a distribution event happened now. */
function getAgentDistributionAmount(uint256 index)
public
view
returns (uint256)
{
require(checkAgentPercentage() == true);
require(index < agents.length);
return
getDistributionAmount()
.mul(agents[index].share)
.div(100);
}
/**
* Distributes the tokens based on the balance and the distribution rate.
*
* Anyone can call, and should call prior to an unstake event.
*/
function distribute() external {
require(distributing == true);
require(checkAgentPercentage() == true);
require(getDistributionAmount() > 0);
for (uint256 i = 0; i < agents.length; i++) {
uint256 amount = getAgentDistributionAmount(i);
if (amount > 0) {
require(token.transfer(agents[i].agent, amount));
}
}
lastDistributionTimestamp = block.timestamp;
}
/**
* Returns the balance to the owner of the contract. This is needed
* if there is a contract upgrade & for testing & validation purposes.
*/
function returnBalance2Owner() external onlyOwner returns (bool) {
uint256 value = balance();
if (value == 0) {
return true;
}
return token.transfer(owner(), value);
}
} | * @notice Sets an Agents share of the distribution. @param _index Index of Agents. Ordering may have changed since adding. @param _share Percentage share of the distribution (can be 0)./ | function setAgentShare(uint256 _index, uint8 _share) external onlyOwner {
require(
_index < agents.length,
"index must be in range of stored tx list"
);
require(_share <= uint8(100));
distributing = false;
agents[_index].share = _share;
}
| 207,241 | [
1,
2785,
392,
5495,
4877,
7433,
434,
326,
7006,
18,
225,
389,
1615,
3340,
434,
5495,
4877,
18,
27582,
2026,
1240,
3550,
3241,
6534,
18,
225,
389,
14419,
21198,
410,
7433,
434,
326,
7006,
261,
4169,
506,
374,
2934,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
3630,
9535,
12,
11890,
5034,
389,
1615,
16,
2254,
28,
389,
14419,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
203,
5411,
389,
1615,
411,
16423,
18,
2469,
16,
203,
5411,
315,
1615,
1297,
506,
316,
1048,
434,
4041,
2229,
666,
6,
203,
3639,
11272,
203,
3639,
2583,
24899,
14419,
1648,
2254,
28,
12,
6625,
10019,
203,
3639,
1015,
665,
8490,
273,
629,
31,
203,
3639,
16423,
63,
67,
1615,
8009,
14419,
273,
389,
14419,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @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 virtual override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @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) external view returns (address);
/**
* @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) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
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 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 {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
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 {
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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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 (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
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;
address private immutable _CACHED_THIS;
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);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, 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: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { ERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
import { Token } from "../token/Token.sol";
import { ERC20Burnable } from "../token/ERC20Burnable.sol";
import { IVersioned } from "../utility/interfaces/IVersioned.sol";
import { Owned } from "../utility/Owned.sol";
import { Utils } from "../utility/Utils.sol";
import { IPoolToken } from "./interfaces/IPoolToken.sol";
/**
* @dev Pool Token contract
*/
contract PoolToken is IPoolToken, ERC20Permit, ERC20Burnable, Owned, Utils {
Token private immutable _reserveToken;
uint8 private _decimals;
/**
* @dev initializes a new PoolToken contract
*/
constructor(
string memory name,
string memory symbol,
uint8 initDecimals,
Token initReserveToken
) ERC20(name, symbol) ERC20Permit(name) validAddress(address(initReserveToken)) {
_decimals = initDecimals;
_reserveToken = initReserveToken;
}
/**
* @inheritdoc IVersioned
*/
function version() external pure returns (uint16) {
return 1;
}
/**
* @dev returns the number of decimals used to get its user representation
*/
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
/**
* @inheritdoc IPoolToken
*/
function reserveToken() external view returns (Token) {
return _reserveToken;
}
/**
* @inheritdoc IPoolToken
*/
function mint(address recipient, uint256 amount) external onlyOwner validExternalAddress(recipient) {
_mint(recipient, amount);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Token } from "../token/Token.sol";
import { TokenLibrary } from "../token/TokenLibrary.sol";
import { IVersioned } from "../utility/interfaces/IVersioned.sol";
import { Upgradeable } from "../utility/Upgradeable.sol";
import { Utils } from "../utility/Utils.sol";
import { IPoolTokenFactory } from "./interfaces/IPoolTokenFactory.sol";
import { IPoolToken } from "./interfaces/IPoolToken.sol";
import { PoolToken } from "./PoolToken.sol";
/**
* @dev Pool Token Factory contract
*/
contract PoolTokenFactory is IPoolTokenFactory, Upgradeable, Utils {
using TokenLibrary for Token;
string private constant POOL_TOKEN_SYMBOL_PREFIX = "bn";
string private constant POOL_TOKEN_NAME_PREFIX = "Bancor";
string private constant POOL_TOKEN_NAME_SUFFIX = "Pool Token";
// a mapping between tokens and custom symbol overrides (only needed for tokens with malformed symbol property)
mapping(Token => string) private _tokenSymbolOverrides;
// a mapping between tokens and custom token overrides (only needed for tokens with malformed decimals property)
mapping(Token => uint8) private _tokenDecimalsOverrides;
// upgrade forward-compatibility storage gap
uint256[MAX_GAP - 2] private __gap;
/**
* @dev triggered when a pool token is created
*/
event PoolTokenCreated(IPoolToken indexed poolToken, Token indexed token);
/**
* @dev fully initializes the contract and its parents
*/
function initialize() external initializer {
__PoolTokenFactory_init();
}
// solhint-disable func-name-mixedcase
/**
* @dev initializes the contract and its parents
*/
function __PoolTokenFactory_init() internal onlyInitializing {
__Upgradeable_init();
__PoolTokenFactory_init_unchained();
}
/**
* @dev performs contract-specific initialization
*/
function __PoolTokenFactory_init_unchained() internal onlyInitializing {}
// solhint-enable func-name-mixedcase
/**
* @inheritdoc Upgradeable
*/
function version() public pure override(IVersioned, Upgradeable) returns (uint16) {
return 1;
}
/**
* @inheritdoc IPoolTokenFactory
*/
function tokenSymbolOverride(Token token) external view returns (string memory) {
return _tokenSymbolOverrides[token];
}
/**
* @dev sets the custom symbol override for a given reserve token
*
* requirements:
*
* - the caller must be the admin of the contract
*/
function setTokenSymbolOverride(Token token, string calldata symbol) external onlyAdmin {
_tokenSymbolOverrides[token] = symbol;
}
/**
* @inheritdoc IPoolTokenFactory
*/
function tokenDecimalsOverride(Token token) external view returns (uint8) {
return _tokenDecimalsOverrides[token];
}
/**
* @dev sets the decimals override for a given reserve token
*
* requirements:
*
* - the caller must be the admin of the contract
*/
function setTokenDecimalsOverride(Token token, uint8 decimals) external onlyAdmin {
_tokenDecimalsOverrides[token] = decimals;
}
/**
* @inheritdoc IPoolTokenFactory
*/
function createPoolToken(Token token) external validAddress(address(token)) returns (IPoolToken) {
string memory customSymbol = _tokenSymbolOverrides[token];
string memory tokenSymbol = bytes(customSymbol).length != 0 ? customSymbol : token.symbol();
uint8 customDecimals = _tokenDecimalsOverrides[token];
uint8 tokenDecimals = customDecimals != 0 ? customDecimals : token.decimals();
string memory symbol = string.concat(POOL_TOKEN_SYMBOL_PREFIX, tokenSymbol);
string memory name = string.concat(POOL_TOKEN_NAME_PREFIX, " ", tokenSymbol, " ", POOL_TOKEN_NAME_SUFFIX);
PoolToken newPoolToken = new PoolToken(name, symbol, tokenDecimals, token);
// make sure to transfer the ownership to the caller
newPoolToken.transferOwnership(msg.sender);
emit PoolTokenCreated({ poolToken: newPoolToken, token: token });
return newPoolToken;
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import { IERC20Burnable } from "../../token/interfaces/IERC20Burnable.sol";
import { Token } from "../../token/Token.sol";
import { IVersioned } from "../../utility/interfaces/IVersioned.sol";
import { IOwned } from "../../utility/interfaces/IOwned.sol";
/**
* @dev Pool Token interface
*/
interface IPoolToken is IVersioned, IOwned, IERC20, IERC20Permit, IERC20Burnable {
/**
* @dev returns the address of the reserve token
*/
function reserveToken() external view returns (Token);
/**
* @dev increases the token supply and sends the new tokens to the given account
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function mint(address recipient, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Token } from "../../token/Token.sol";
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { IPoolToken } from "./IPoolToken.sol";
/**
* @dev Pool Token Factory interface
*/
interface IPoolTokenFactory is IUpgradeable {
/**
* @dev returns the custom symbol override for a given reserve token
*/
function tokenSymbolOverride(Token token) external view returns (string memory);
/**
* @dev returns the custom decimals override for a given reserve token
*/
function tokenDecimalsOverride(Token token) external view returns (uint8);
/**
* @dev creates a pool token for the specified token
*/
function createPoolToken(Token token) external returns (IPoolToken);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20Burnable } from "./interfaces/IERC20Burnable.sol";
/**
* @dev this is an adapted clone of the OZ's ERC20Burnable extension which is unfortunately required so that it can be
* explicitly specified in interfaces via our new IERC20Burnable interface.
*
* We have also removed the explicit use of Context and updated the code to our style.
*/
abstract contract ERC20Burnable is ERC20, IERC20Burnable {
/**
* @inheritdoc IERC20Burnable
*/
function burn(uint256 amount) external virtual {
_burn(msg.sender, amount);
}
/**
* @inheritdoc IERC20Burnable
*/
function burnFrom(address recipient, uint256 amount) external virtual {
_approve(recipient, msg.sender, allowance(recipient, msg.sender) - amount);
_burn(recipient, amount);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @dev extends the SafeERC20 library with additional operations
*/
library SafeERC20Ex {
using SafeERC20 for IERC20;
/**
* @dev ensures that the spender has sufficient allowance
*/
function ensureApprove(
IERC20 token,
address spender,
uint256 amount
) internal {
if (amount == 0) {
return;
}
uint256 allowance = token.allowance(address(this), spender);
if (allowance >= amount) {
return;
}
if (allowance > 0) {
token.safeApprove(spender, 0);
}
token.safeApprove(spender, amount);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev the main purpose of the Token interfaces is to ensure artificially that we won't use ERC20's standard functions,
* but only their safe versions, which are provided by SafeERC20 and SafeERC20Ex via the TokenLibrary contract
*/
interface Token {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import { SafeERC20Ex } from "./SafeERC20Ex.sol";
import { Token } from "./Token.sol";
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
/**
* @dev This library implements ERC20 and SafeERC20 utilities for both the native token and for ERC20 tokens
*/
library TokenLibrary {
using SafeERC20 for IERC20;
using SafeERC20Ex for IERC20;
error PermitUnsupported();
// the address that represents the native token reserve
address public constant NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// the symbol that represents the native token
string private constant NATIVE_TOKEN_SYMBOL = "ETH";
// the decimals for the native token
uint8 private constant NATIVE_TOKEN_DECIMALS = 18;
/**
* @dev returns whether the provided token represents an ERC20 or the native token reserve
*/
function isNative(Token token) internal pure returns (bool) {
return address(token) == NATIVE_TOKEN_ADDRESS;
}
/**
* @dev returns the symbol of the native token/ERC20 token
*/
function symbol(Token token) internal view returns (string memory) {
if (isNative(token)) {
return NATIVE_TOKEN_SYMBOL;
}
return toERC20(token).symbol();
}
/**
* @dev returns the decimals of the native token/ERC20 token
*/
function decimals(Token token) internal view returns (uint8) {
if (isNative(token)) {
return NATIVE_TOKEN_DECIMALS;
}
return toERC20(token).decimals();
}
/**
* @dev returns the balance of the native token/ERC20 token
*/
function balanceOf(Token token, address account) internal view returns (uint256) {
if (isNative(token)) {
return account.balance;
}
return toIERC20(token).balanceOf(account);
}
/**
* @dev transfers a specific amount of the native token/ERC20 token
*/
function safeTransfer(
Token token,
address to,
uint256 amount
) internal {
if (amount == 0) {
return;
}
if (isNative(token)) {
payable(to).transfer(amount);
} else {
toIERC20(token).safeTransfer(to, amount);
}
}
/**
* @dev transfers a specific amount of the native token/ERC20 token from a specific holder using the allowance mechanism
*
* note that the function does not perform any action if the native token is provided
*/
function safeTransferFrom(
Token token,
address from,
address to,
uint256 amount
) internal {
if (amount == 0 || isNative(token)) {
return;
}
toIERC20(token).safeTransferFrom(from, to, amount);
}
/**
* @dev approves a specific amount of the native token/ERC20 token from a specific holder
*
* note that the function does not perform any action if the native token is provided
*/
function safeApprove(
Token token,
address spender,
uint256 amount
) internal {
if (isNative(token)) {
return;
}
toIERC20(token).safeApprove(spender, amount);
}
/**
* @dev ensures that the spender has sufficient allowance
*
* note that the function does not perform any action if the native token is provided
*/
function ensureApprove(
Token token,
address spender,
uint256 amount
) internal {
if (isNative(token)) {
return;
}
toIERC20(token).ensureApprove(spender, amount);
}
/**
* @dev performs an EIP2612 permit
*/
function permit(
Token token,
address owner,
address spender,
uint256 tokenAmount,
uint256 deadline,
Signature memory signature
) internal {
if (isNative(token)) {
revert PermitUnsupported();
}
// permit the amount the owner is trying to deposit. Please note, that if the base token doesn't support
// EIP2612 permit - either this call or the inner safeTransferFrom will revert
IERC20Permit(address(token)).permit(
owner,
spender,
tokenAmount,
deadline,
signature.v,
signature.r,
signature.s
);
}
/**
* @dev compares between a token and another raw ERC20 token
*/
function isEqual(Token token, IERC20 erc20Token) internal pure returns (bool) {
return toIERC20(token) == erc20Token;
}
/**
* @dev utility function that converts an token to an IERC20
*/
function toIERC20(Token token) internal pure returns (IERC20) {
return IERC20(address(token));
}
/**
* @dev utility function that converts an token to an ERC20
*/
function toERC20(Token token) internal pure returns (ERC20) {
return ERC20(address(token));
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev burnable ERC20 interface
*/
interface IERC20Burnable {
/**
* @dev Destroys tokens from the caller.
*/
function burn(uint256 amount) external;
/**
* @dev Destroys tokens from a recipient, deducting from the caller's allowance
*
* requirements:
*
* - the caller must have allowance for recipient's tokens of at least the specified amount
*/
function burnFrom(address recipient, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
uint32 constant PPM_RESOLUTION = 1000000;
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IOwned } from "./interfaces/IOwned.sol";
import { AccessDenied } from "./Utils.sol";
/**
* @dev this contract provides support and utilities for contract ownership
*/
abstract contract Owned is IOwned {
error SameOwner();
address private _owner;
address private _newOwner;
/**
* @dev triggered when the owner is updated
*/
event OwnerUpdate(address indexed prevOwner, address indexed newOwner);
// solhint-disable func-name-mixedcase
/**
* @dev initializes the contract
*/
constructor() {
_transferOwnership(msg.sender);
}
// solhint-enable func-name-mixedcase
// allows execution by the owner only
modifier onlyOwner() {
_onlyOwner();
_;
}
// error message binary size optimization
function _onlyOwner() private view {
if (msg.sender != _owner) {
revert AccessDenied();
}
}
/**
* @inheritdoc IOwned
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @inheritdoc IOwned
*/
function transferOwnership(address ownerCandidate) public virtual onlyOwner {
if (ownerCandidate == _owner) {
revert SameOwner();
}
_newOwner = ownerCandidate;
}
/**
* @inheritdoc IOwned
*/
function acceptOwnership() public virtual {
if (msg.sender != _newOwner) {
revert AccessDenied();
}
_transferOwnership(_newOwner);
}
/**
* @dev returns the address of the new owner candidate
*/
function newOwner() external view returns (address) {
return _newOwner;
}
/**
* @dev sets the new owner internally
*/
function _transferOwnership(address ownerCandidate) private {
address prevOwner = _owner;
_owner = ownerCandidate;
_newOwner = address(0);
emit OwnerUpdate({ prevOwner: prevOwner, newOwner: ownerCandidate });
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { AccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import { IUpgradeable } from "./interfaces/IUpgradeable.sol";
import { AccessDenied } from "./Utils.sol";
/**
* @dev this contract provides common utilities for upgradeable contracts
*/
abstract contract Upgradeable is IUpgradeable, AccessControlEnumerableUpgradeable {
error AlreadyInitialized();
// the admin role is used to allow a non-proxy admin to perform additional initialization/setup during contract
// upgrades
bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN");
uint32 internal constant MAX_GAP = 50;
uint16 internal _initializations;
// upgrade forward-compatibility storage gap
uint256[MAX_GAP - 1] private __gap;
// solhint-disable func-name-mixedcase
/**
* @dev initializes the contract and its parents
*/
function __Upgradeable_init() internal onlyInitializing {
__AccessControl_init();
__Upgradeable_init_unchained();
}
/**
* @dev performs contract-specific initialization
*/
function __Upgradeable_init_unchained() internal onlyInitializing {
_initializations = 1;
// set up administrative roles
_setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN);
// allow the deployer to initially be the admin of the contract
_setupRole(ROLE_ADMIN, msg.sender);
}
// solhint-enable func-name-mixedcase
modifier onlyAdmin() {
_hasRole(ROLE_ADMIN, msg.sender);
_;
}
modifier onlyRoleMember(bytes32 role) {
_hasRole(role, msg.sender);
_;
}
function version() public view virtual override returns (uint16);
/**
* @dev returns the admin role
*/
function roleAdmin() external pure returns (bytes32) {
return ROLE_ADMIN;
}
/**
* @dev performs post-upgrade initialization
*
* requirements:
*
* - this must can be called only once per-upgrade
*/
function postUpgrade(bytes calldata data) external {
uint16 initializations = _initializations + 1;
if (initializations != version()) {
revert AlreadyInitialized();
}
_initializations = initializations;
_postUpgrade(data);
}
/**
* @dev an optional post-upgrade callback that can be implemented by child contracts
*/
function _postUpgrade(
bytes calldata /* data */
) internal virtual {}
function _hasRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert AccessDenied();
}
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { PPM_RESOLUTION } from "./Constants.sol";
error AccessDenied();
error AlreadyExists();
error DoesNotExist();
error InvalidAddress();
error InvalidExternalAddress();
error InvalidFee();
error InvalidPool();
error InvalidPoolCollection();
error InvalidStakedBalance();
error InvalidToken();
error InvalidType();
error InvalidParam();
error NotEmpty();
error NotPayable();
error ZeroValue();
/**
* @dev common utilities
*/
contract Utils {
// allows execution by the caller only
modifier only(address caller) {
_only(caller);
_;
}
function _only(address caller) internal view {
if (msg.sender != caller) {
revert AccessDenied();
}
}
// verifies that a value is greater than zero
modifier greaterThanZero(uint256 value) {
_greaterThanZero(value);
_;
}
// error message binary size optimization
function _greaterThanZero(uint256 value) internal pure {
if (value == 0) {
revert ZeroValue();
}
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address addr) {
_validAddress(addr);
_;
}
// error message binary size optimization
function _validAddress(address addr) internal pure {
if (addr == address(0)) {
revert InvalidAddress();
}
}
// validates an external address - currently only checks that it isn't null or this
modifier validExternalAddress(address addr) {
_validExternalAddress(addr);
_;
}
// error message binary size optimization
function _validExternalAddress(address addr) internal view {
if (addr == address(0) || addr == address(this)) {
revert InvalidExternalAddress();
}
}
// ensures that the fee is valid
modifier validFee(uint32 fee) {
_validFee(fee);
_;
}
// error message binary size optimization
function _validFee(uint32 fee) internal pure {
if (fee > PPM_RESOLUTION) {
revert InvalidFee();
}
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev Owned interface
*/
interface IOwned {
/**
* @dev returns the address of the current owner
*/
function owner() external view returns (address);
/**
* @dev allows transferring the contract ownership
*
* requirements:
*
* - the caller must be the owner of the contract
* - the new owner still needs to accept the transfer
*/
function transferOwnership(address ownerCandidate) external;
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVersioned } from "./IVersioned.sol";
import { IAccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/IAccessControlEnumerableUpgradeable.sol";
/**
* @dev this is the common interface for upgradeable contracts
*/
interface IUpgradeable is IAccessControlEnumerableUpgradeable, IVersioned {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev an interface for a versioned contract
*/
interface IVersioned {
function version() external view returns (uint16);
} | * @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 for more information./ | function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
return _roleMembers[role].at(index);
}
| 86,748 | [
1,
1356,
1245,
434,
326,
9484,
716,
1240,
1375,
4615,
8338,
1375,
1615,
68,
1297,
506,
279,
460,
3086,
374,
471,
288,
588,
2996,
4419,
1380,
5779,
1661,
17,
267,
9173,
18,
6204,
506,
297,
414,
854,
486,
3115,
316,
1281,
6826,
4031,
16,
471,
3675,
9543,
2026,
2549,
622,
1281,
1634,
18,
9744,
30,
5203,
1450,
288,
588,
2996,
4419,
97,
471,
288,
588,
2996,
4419,
1380,
5779,
1221,
3071,
1846,
3073,
777,
6218,
603,
326,
1967,
1203,
18,
2164,
326,
3751,
364,
1898,
1779,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
15673,
4419,
12,
3890,
1578,
2478,
16,
2254,
5034,
770,
13,
1071,
1476,
5024,
3849,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
4615,
6918,
63,
4615,
8009,
270,
12,
1615,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "../../lib/date/BokkyPooBahsDateTimeLibrary.sol";
/**
* @title DateTime
* @dev Library with convenience functions for working with datetime and timestamp values.
* Wraps calls to BokkyPooBahsDateTimeLibrary library (https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary).
*/
library DateTime {
uint constant SECONDS_PER_HOUR = 60 * 60;
uint constant SECONDS_PER_MINUTE = 60;
/// Code based on https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
function isValidYearAndMonth(uint year, uint month) internal pure returns (bool) {
return (year >= 1970 && month > 0 && month <= 12);
}
/// Code based on https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
function isValidTime(uint hour, uint minute, uint second) internal pure returns (bool) {
return (hour < 24 && minute < 60 && second < 60);
}
function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool) {
return BokkyPooBahsDateTimeLibrary.isValidDateTime(year, month, day, hour, minute, second);
}
// note that no overflow check is performed. Make sure to call "isValidTime" prior to using this function
function totalSeconds(uint hour, uint minute, uint second) internal pure returns (uint) {
return
hour * SECONDS_PER_HOUR +
minute * SECONDS_PER_MINUTE +
second;
}
// BokkyPooBahsDateTimeLibrary call does check for overflow
function add(uint timestamp, uint _seconds) internal pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addSeconds(timestamp, _seconds);
}
function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, month, day);
}
function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.timestampFromDateTime(year, month, day, hour, minute, second);
}
// returns the Min between the provided day and total days in the given month
function constrainToDaysInMonth(uint year, uint month, uint day) internal pure returns (uint adjustedPaymentDay) {
adjustedPaymentDay = day;
if (adjustedPaymentDay > 28) {
uint daysInMonth = BokkyPooBahsDateTimeLibrary._getDaysInMonth(year, month);
if (adjustedPaymentDay > daysInMonth) {
adjustedPaymentDay = daysInMonth;
}
}
}
} | Code based on https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary | function isValidYearAndMonth(uint year, uint month) internal pure returns (bool) {
return (year >= 1970 && month > 0 && month <= 12);
}
| 12,912,289 | [
1,
1085,
2511,
603,
2333,
2207,
6662,
18,
832,
19,
70,
601,
79,
879,
83,
947,
9795,
19,
38,
601,
18465,
52,
5161,
38,
69,
4487,
5096,
9313,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4908,
5593,
1876,
5445,
12,
11890,
3286,
16,
2254,
3138,
13,
2713,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
327,
261,
6874,
1545,
5342,
7301,
597,
3138,
405,
374,
597,
3138,
1648,
2593,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/interfaces/IERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Account is Ownable{
using SafeMath for uint256;
struct Token {
bytes32 ticker;
address tokenAddress;
}
bytes32[] public tokenList; //List of the tickers
mapping(bytes32 => Token) public tokens;
mapping(address => mapping(bytes32 => uint256)) public balances; //bytes will be used to track the different tokens
mapping(address => bool) contractWhitelist;
modifier tokenAddressCheck(bytes32 _ticker) {
require(tokens[_ticker].tokenAddress != address(0), 'This token isnt supported');
_;
}
function addContract(address _contract) onlyOwner external {
contractWhitelist[_contract] = true;
}
function editBalances(address _account, bytes32 _ticker, uint256 _amount) external {
require(contractWhitelist[msg.sender] == true, 'address isnt whitelisted to interact with accounts');
balances[_account][_ticker] = _amount;
}
function returnBalances(address _accountAddress, bytes32 _ticker) public view returns (uint256) {
return balances[_accountAddress][_ticker];
}
function addToken(bytes32 _ticker, address _tokenAddress) onlyOwner external { //use external to save gas, because we won't need to call this function inside the contract
tokens[_ticker] = Token(_ticker, _tokenAddress);
tokenList.push(_ticker);
}
function deposit(uint256 _amount, bytes32 _ticker) tokenAddressCheck(_ticker) external {
IERC20(tokens[_ticker].tokenAddress).transferFrom(msg.sender, address(this), _amount); //Need a seperate approve function to happen for this to be able to go through obviously
balances[msg.sender][_ticker] = balances[msg.sender][_ticker].add(_amount);
}
function withdraw(uint256 _amount, bytes32 _ticker) tokenAddressCheck(_ticker) external {
require(balances[msg.sender][_ticker] >= _amount, 'User doesnt have enough balance to withdraw this amount');
balances[msg.sender][_ticker] = balances[msg.sender][_ticker].sub(_amount);
IERC20(tokens[_ticker].tokenAddress).transfer(msg.sender, _amount);
}
}
| bytes will be used to track the different tokens
| mapping(address => mapping(bytes32 => uint256)) public balances; | 5,412,241 | [
1,
3890,
903,
506,
1399,
358,
3298,
326,
3775,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
2867,
516,
2874,
12,
3890,
1578,
516,
2254,
5034,
3719,
1071,
324,
26488,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x6B3BC3fa94c619970B50c6EB95B4fBD728AeC80c/sources/GREEN.sol | when buywhen sell if any account belongs to _isExcludedFromFee account then remove the fee only take fees on buys/sells, do not take on wallet transfers on sell on buy | function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!isBlacklisted[msg.sender], "Sender is blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(areLimitsOn){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!isSwppable
){
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransaction, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWalletHolding, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransaction, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWalletHolding, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= contractSellTreshold;
if(
canSwap &&
!isSwppable &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
isSwppable = true;
swapBack();
isSwppable = false;
}
bool takeFee = !isSwppable;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && totalSellTax > 0){
fees = amount.mul(totalSellTax).div(100);
tokensForLiquidity += fees * liqSellTax / totalSellTax;
tokensForDev += fees * devSellTax / totalSellTax;
}
else if(automatedMarketMakerPairs[from] && totalBuyTax > 0) {
fees = amount.mul(totalBuyTax).div(100);
tokensForLiquidity += fees * liqBuyTax / totalBuyTax;
tokensForDev += fees * devBuyTax / totalBuyTax;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
| 2,822,430 | [
1,
13723,
30143,
13723,
357,
80,
309,
1281,
2236,
11081,
358,
389,
291,
16461,
1265,
14667,
2236,
1508,
1206,
326,
14036,
1338,
4862,
1656,
281,
603,
25666,
1900,
19,
87,
1165,
87,
16,
741,
486,
4862,
603,
9230,
29375,
603,
357,
80,
603,
30143,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
3849,
288,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
5,
291,
13155,
18647,
63,
3576,
18,
15330,
6487,
315,
12021,
353,
25350,
8863,
203,
540,
203,
540,
309,
12,
8949,
422,
374,
13,
288,
203,
5411,
2240,
6315,
13866,
12,
2080,
16,
358,
16,
374,
1769,
203,
5411,
327,
31,
203,
3639,
289,
203,
7010,
3639,
309,
12,
834,
12768,
1398,
15329,
203,
5411,
309,
261,
203,
7734,
628,
480,
3410,
1435,
597,
203,
7734,
358,
480,
3410,
1435,
597,
203,
7734,
358,
480,
1758,
12,
20,
13,
597,
203,
7734,
358,
480,
1758,
12,
20,
92,
22097,
13,
597,
203,
7734,
401,
291,
6050,
11858,
429,
203,
5411,
262,
95,
203,
1171,
203,
7734,
309,
261,
5854,
362,
690,
3882,
278,
12373,
10409,
63,
2080,
65,
597,
401,
67,
291,
16461,
2747,
3342,
6275,
63,
869,
5717,
288,
203,
13491,
2583,
12,
8949,
1648,
943,
3342,
16,
315,
38,
9835,
7412,
3844,
14399,
326,
943,
3342,
6275,
1199,
1769,
203,
13491,
2583,
12,
8949,
397,
11013,
951,
12,
869,
13,
1648,
943,
16936,
20586,
310,
16,
315,
2747,
9230,
12428,
8863,
203,
7734,
289,
203,
7010,
7734,
469,
309,
261,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract 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());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// 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 ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns 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 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.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view 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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// 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 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);
}
/**
* @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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./IVaultHandler.sol";
import "./Orchestrator.sol";
/**
* @title ERC-20 TCAP Vault
* @author Cryptex.finance
* @notice Contract in charge of handling the TCAP Vault and stake using a Collateral ERC20
*/
contract ERC20VaultHandler is IVaultHandler {
/**
* @notice Constructor
* @param _orchestrator address
* @param _divisor uint256
* @param _ratio uint256
* @param _burnFee uint256
* @param _liquidationPenalty uint256
* @param _tcapOracle address
* @param _tcapAddress address
* @param _collateralAddress address
* @param _collateralOracle address
* @param _ethOracle address
* @param _rewardHandler address
* @param _treasury address
*/
constructor(
Orchestrator _orchestrator,
uint256 _divisor,
uint256 _ratio,
uint256 _burnFee,
uint256 _liquidationPenalty,
address _tcapOracle,
TCAP _tcapAddress,
address _collateralAddress,
address _collateralOracle,
address _ethOracle,
address _rewardHandler,
address _treasury
)
IVaultHandler(
_orchestrator,
_divisor,
_ratio,
_burnFee,
_liquidationPenalty,
_tcapOracle,
_tcapAddress,
_collateralAddress,
_collateralOracle,
_ethOracle,
_rewardHandler,
_treasury
)
{}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
import "./TCAP.sol";
import "./Orchestrator.sol";
import "./oracles/ChainlinkOracle.sol";
interface IRewardHandler {
function stake(address _staker, uint256 amount) external;
function withdraw(address _staker, uint256 amount) external;
function getRewardFromVault(address _staker) external;
}
/**
* @title TCAP Vault Handler Abstract Contract
* @author Cryptex.Finance
* @notice Contract in charge of handling the TCAP Token and stake
*/
abstract contract IVaultHandler is
Ownable,
AccessControl,
ReentrancyGuard,
Pausable,
IERC165
{
/// @notice Open Zeppelin libraries
using SafeMath for uint256;
using SafeCast for int256;
using Counters for Counters.Counter;
using SafeERC20 for IERC20;
/**
* @notice Vault object created to manage the mint and burns of TCAP tokens
* @param Id, unique identifier of the vault
* @param Collateral, current collateral on vault
* @param Debt, current amount of TCAP tokens minted
* @param Owner, owner of the vault
*/
struct Vault {
uint256 Id;
uint256 Collateral;
uint256 Debt;
address Owner;
}
/// @notice Vault Id counter
Counters.Counter public counter;
/// @notice TCAP Token Address
TCAP public immutable TCAPToken;
/// @notice Total Market Cap/USD Oracle Address
ChainlinkOracle public immutable tcapOracle;
/// @notice Collateral Token Address
IERC20 public immutable collateralContract;
/// @notice Collateral/USD Oracle Address
ChainlinkOracle public immutable collateralPriceOracle;
/// @notice ETH/USD Oracle Address
ChainlinkOracle public immutable ETHPriceOracle;
/// @notice Value used as divisor with the total market cap, just like the S&P 500 or any major financial index would to define the final tcap token price
uint256 public divisor;
/// @notice Minimun ratio required to prevent liquidation of vault
uint256 public ratio;
/// @notice Fee percentage of the total amount to burn charged on ETH when burning TCAP Tokens
uint256 public burnFee;
/// @notice Penalty charged to vault owner when a vault is liquidated, this value goes to the liquidator
uint256 public liquidationPenalty;
/// @notice Address of the contract that gives rewards to minters of TCAP, rewards are only given if address is set in constructor
IRewardHandler public immutable rewardHandler;
/// @notice Address of the treasury contract (usually the timelock) where the funds generated by the protocol are sent
address public treasury;
/// @notice Owner address to Vault Id
mapping(address => uint256) public userToVault;
/// @notice Id To Vault
mapping(uint256 => Vault) public vaults;
/// @notice value used to multiply chainlink oracle for handling decimals
uint256 public constant oracleDigits = 10000000000;
/// @notice Minimum value that the ratio can be set to
uint256 public constant MIN_RATIO = 150;
/// @notice Maximum value that the burn fee can be set to
uint256 public constant MAX_FEE = 10;
/**
* @dev the computed interface ID according to ERC-165. The interface ID is a XOR of interface method selectors.
* setRatio.selector ^
* setBurnFee.selector ^
* setLiquidationPenalty.selector ^
* pause.selector ^
* unpause.selector => 0x9e75ab0c
*/
bytes4 private constant _INTERFACE_ID_IVAULT = 0x9e75ab0c;
/// @dev bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/// @notice An event emitted when the ratio is updated
event NewRatio(address indexed _owner, uint256 _ratio);
/// @notice An event emitted when the burn fee is updated
event NewBurnFee(address indexed _owner, uint256 _burnFee);
/// @notice An event emitted when the liquidation penalty is updated
event NewLiquidationPenalty(
address indexed _owner,
uint256 _liquidationPenalty
);
/// @notice An event emitted when the treasury contract is updated
event NewTreasury(address indexed _owner, address _tresury);
/// @notice An event emitted when a vault is created
event VaultCreated(address indexed _owner, uint256 indexed _id);
/// @notice An event emitted when collateral is added to a vault
event CollateralAdded(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when collateral is removed from a vault
event CollateralRemoved(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when tokens are minted
event TokensMinted(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when tokens are burned
event TokensBurned(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when a vault is liquidated
event VaultLiquidated(
uint256 indexed _vaultId,
address indexed _liquidator,
uint256 _liquidationCollateral,
uint256 _reward
);
/// @notice An event emitted when a erc20 token is recovered
event Recovered(address _token, uint256 _amount);
/**
* @notice Constructor
* @param _orchestrator address
* @param _divisor uint256
* @param _ratio uint256
* @param _burnFee uint256
* @param _liquidationPenalty uint256
* @param _tcapOracle address
* @param _tcapAddress address
* @param _collateralAddress address
* @param _collateralOracle address
* @param _ethOracle address
* @param _rewardHandler address
* @param _treasury address
*/
constructor(
Orchestrator _orchestrator,
uint256 _divisor,
uint256 _ratio,
uint256 _burnFee,
uint256 _liquidationPenalty,
address _tcapOracle,
TCAP _tcapAddress,
address _collateralAddress,
address _collateralOracle,
address _ethOracle,
address _rewardHandler,
address _treasury
) {
require(
_liquidationPenalty.add(100) < _ratio,
"VaultHandler::constructor: liquidation penalty too high"
);
require(
_ratio >= MIN_RATIO,
"VaultHandler::constructor: ratio lower than MIN_RATIO"
);
require(
_burnFee <= MAX_FEE,
"VaultHandler::constructor: burn fee higher than MAX_FEE"
);
divisor = _divisor;
ratio = _ratio;
burnFee = _burnFee;
liquidationPenalty = _liquidationPenalty;
tcapOracle = ChainlinkOracle(_tcapOracle);
collateralContract = IERC20(_collateralAddress);
collateralPriceOracle = ChainlinkOracle(_collateralOracle);
ETHPriceOracle = ChainlinkOracle(_ethOracle);
TCAPToken = _tcapAddress;
rewardHandler = IRewardHandler(_rewardHandler);
treasury = _treasury;
/// @dev counter starts in 1 as 0 is reserved for empty objects
counter.increment();
/// @dev transfer ownership to orchestrator
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
transferOwnership(address(_orchestrator));
}
/// @notice Reverts if the user hasn't created a vault.
modifier vaultExists() {
require(
userToVault[msg.sender] != 0,
"VaultHandler::vaultExists: no vault created"
);
_;
}
/// @notice Reverts if value is 0.
modifier notZero(uint256 _value) {
require(_value != 0, "VaultHandler::notZero: value can't be 0");
_;
}
/**
* @notice Sets the collateral ratio needed to mint tokens
* @param _ratio uint
* @dev Only owner can call it
*/
function setRatio(uint256 _ratio) external virtual onlyOwner {
require(
_ratio >= MIN_RATIO,
"VaultHandler::setRatio: ratio lower than MIN_RATIO"
);
ratio = _ratio;
emit NewRatio(msg.sender, _ratio);
}
/**
* @notice Sets the burn fee percentage an user pays when burning tcap tokens
* @param _burnFee uint
* @dev Only owner can call it
*/
function setBurnFee(uint256 _burnFee) external virtual onlyOwner {
require(
_burnFee <= MAX_FEE,
"VaultHandler::setBurnFee: burn fee higher than MAX_FEE"
);
burnFee = _burnFee;
emit NewBurnFee(msg.sender, _burnFee);
}
/**
* @notice Sets the liquidation penalty % charged on liquidation
* @param _liquidationPenalty uint
* @dev Only owner can call it
* @dev recommended value is between 1-15% and can't be above 100%
*/
function setLiquidationPenalty(uint256 _liquidationPenalty)
external
virtual
onlyOwner
{
require(
_liquidationPenalty.add(100) < ratio,
"VaultHandler::setLiquidationPenalty: liquidation penalty too high"
);
liquidationPenalty = _liquidationPenalty;
emit NewLiquidationPenalty(msg.sender, _liquidationPenalty);
}
/**
* @notice Sets the treasury contract address where fees are transfered to
* @param _treasury address
* @dev Only owner can call it
*/
function setTreasury(address _treasury) external virtual onlyOwner {
require(
_treasury != address(0),
"VaultHandler::setTreasury: not a valid treasury"
);
treasury = _treasury;
emit NewTreasury(msg.sender, _treasury);
}
/**
* @notice Allows an user to create an unique Vault
* @dev Only one vault per address can be created
*/
function createVault() external virtual whenNotPaused {
require(
userToVault[msg.sender] == 0,
"VaultHandler::createVault: vault already created"
);
uint256 id = counter.current();
userToVault[msg.sender] = id;
Vault memory vault = Vault(id, 0, 0, msg.sender);
vaults[id] = vault;
counter.increment();
emit VaultCreated(msg.sender, id);
}
/**
* @notice Allows users to add collateral to their vaults
* @param _amount of collateral to be added
* @dev _amount should be higher than 0
* @dev ERC20 token must be approved first
*/
function addCollateral(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
require(
collateralContract.transferFrom(msg.sender, address(this), _amount),
"VaultHandler::addCollateral: ERC20 transfer did not succeed"
);
Vault storage vault = vaults[userToVault[msg.sender]];
vault.Collateral = vault.Collateral.add(_amount);
emit CollateralAdded(msg.sender, vault.Id, _amount);
}
/**
* @notice Allows users to remove collateral currently not being used to generate TCAP tokens from their vaults
* @param _amount of collateral to remove
* @dev reverts if the resulting ratio is less than the minimun ratio
* @dev _amount should be higher than 0
* @dev transfers the collateral back to the user
*/
function removeCollateral(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
Vault storage vault = vaults[userToVault[msg.sender]];
uint256 currentRatio = getVaultRatio(vault.Id);
require(
vault.Collateral >= _amount,
"VaultHandler::removeCollateral: retrieve amount higher than collateral"
);
vault.Collateral = vault.Collateral.sub(_amount);
if (currentRatio != 0) {
require(
getVaultRatio(vault.Id) >= ratio,
"VaultHandler::removeCollateral: collateral below min required ratio"
);
}
require(
collateralContract.transfer(msg.sender, _amount),
"VaultHandler::removeCollateral: ERC20 transfer did not succeed"
);
emit CollateralRemoved(msg.sender, vault.Id, _amount);
}
/**
* @notice Uses collateral to generate debt on TCAP Tokens which are minted and assigend to caller
* @param _amount of tokens to mint
* @dev _amount should be higher than 0
* @dev requires to have a vault ratio above the minimum ratio
* @dev if reward handler is set stake to earn rewards
*/
function mint(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
Vault storage vault = vaults[userToVault[msg.sender]];
uint256 collateral = requiredCollateral(_amount);
require(
vault.Collateral >= collateral,
"VaultHandler::mint: not enough collateral"
);
vault.Debt = vault.Debt.add(_amount);
require(
getVaultRatio(vault.Id) >= ratio,
"VaultHandler::mint: collateral below min required ratio"
);
if (address(rewardHandler) != address(0)) {
rewardHandler.stake(msg.sender, _amount);
}
TCAPToken.mint(msg.sender, _amount);
emit TokensMinted(msg.sender, vault.Id, _amount);
}
/**
* @notice Pays the debt of TCAP tokens resulting them on burn, this releases collateral up to minimun vault ratio
* @param _amount of tokens to burn
* @dev _amount should be higher than 0
* @dev A fee of exactly burnFee must be sent as value on ETH
* @dev The fee goes to the treasury contract
* @dev if reward handler is set exit rewards
*/
function burn(uint256 _amount)
external
payable
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
uint256 fee = getFee(_amount);
require(
msg.value >= fee,
"VaultHandler::burn: burn fee less than required"
);
Vault memory vault = vaults[userToVault[msg.sender]];
_burn(vault.Id, _amount);
if (address(rewardHandler) != address(0)) {
rewardHandler.withdraw(msg.sender, _amount);
rewardHandler.getRewardFromVault(msg.sender);
}
safeTransferETH(treasury, fee);
//send back ETH above fee
safeTransferETH(msg.sender, msg.value.sub(fee));
emit TokensBurned(msg.sender, vault.Id, _amount);
}
/**
* @notice Allow users to burn TCAP tokens to liquidate vaults with vault collateral ratio under the minium ratio, the liquidator receives the staked collateral of the liquidated vault at a premium
* @param _vaultId to liquidate
* @param _maxTCAP max amount of TCAP the liquidator is willing to pay to liquidate vault
* @dev Resulting ratio must be above or equal minimun ratio
* @dev A fee of exactly burnFee must be sent as value on ETH
* @dev The fee goes to the treasury contract
*/
function liquidateVault(uint256 _vaultId, uint256 _maxTCAP)
external
payable
nonReentrant
whenNotPaused
{
Vault storage vault = vaults[_vaultId];
require(vault.Id != 0, "VaultHandler::liquidateVault: no vault created");
uint256 vaultRatio = getVaultRatio(vault.Id);
require(
vaultRatio < ratio,
"VaultHandler::liquidateVault: vault is not liquidable"
);
uint256 requiredTCAP = requiredLiquidationTCAP(vault.Id);
require(
_maxTCAP >= requiredTCAP,
"VaultHandler::liquidateVault: liquidation amount different than required"
);
uint256 fee = getFee(requiredTCAP);
require(
msg.value >= fee,
"VaultHandler::liquidateVault: burn fee less than required"
);
uint256 reward = liquidationReward(vault.Id);
_burn(vault.Id, requiredTCAP);
//Removes the collateral that is rewarded to liquidator
vault.Collateral = vault.Collateral.sub(reward);
// Triggers update of CTX Rewards
if (address(rewardHandler) != address(0)) {
rewardHandler.withdraw(vault.Owner, requiredTCAP);
}
require(
collateralContract.transfer(msg.sender, reward),
"VaultHandler::liquidateVault: ERC20 transfer did not succeed"
);
safeTransferETH(treasury, fee);
//send back ETH above fee
safeTransferETH(msg.sender, msg.value.sub(fee));
emit VaultLiquidated(vault.Id, msg.sender, requiredTCAP, reward);
}
/**
* @notice Allows the owner to Pause the Contract
*/
function pause() external onlyOwner {
_pause();
}
/**
* @notice Allows the owner to Unpause the Contract
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* @notice Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
* @param _tokenAddress address
* @param _tokenAmount uint
* @dev Only owner can call it
*/
function recoverERC20(address _tokenAddress, uint256 _tokenAmount)
external
onlyOwner
{
// Cannot recover the collateral token
require(
_tokenAddress != address(collateralContract),
"Cannot withdraw the collateral tokens"
);
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/**
* @notice Allows the safe transfer of ETH
* @param _to account to transfer ETH
* @param _value amount of ETH
*/
function safeTransferETH(address _to, uint256 _value) internal {
(bool success, ) = _to.call{value: _value}(new bytes(0));
require(success, "ETHVaultHandler::safeTransferETH: ETH transfer failed");
}
/**
* @notice ERC165 Standard for support of interfaces
* @param _interfaceId bytes of interface
* @return bool
*/
function supportsInterface(bytes4 _interfaceId)
external
pure
override
returns (bool)
{
return (_interfaceId == _INTERFACE_ID_IVAULT ||
_interfaceId == _INTERFACE_ID_ERC165);
}
/**
* @notice Returns the Vault information of specified identifier
* @param _id of vault
* @return Id, Collateral, Owner, Debt
*/
function getVault(uint256 _id)
external
view
virtual
returns (
uint256,
uint256,
address,
uint256
)
{
Vault memory vault = vaults[_id];
return (vault.Id, vault.Collateral, vault.Owner, vault.Debt);
}
/**
* @notice Returns the price of the chainlink oracle multiplied by the digits to get 18 decimals format
* @param _oracle to be the price called
* @return price
*/
function getOraclePrice(ChainlinkOracle _oracle)
public
view
virtual
returns (uint256 price)
{
price = _oracle.getLatestAnswer().toUint256().mul(oracleDigits);
}
/**
* @notice Returns the price of the TCAP token
* @return price of the TCAP Token
* @dev TCAP token is 18 decimals
* @dev oracle totalMarketPrice must be in wei format
* @dev P = T / d
* P = TCAP Token Price
* T = Total Crypto Market Cap
* d = Divisor
*/
function TCAPPrice() public view virtual returns (uint256 price) {
uint256 totalMarketPrice = getOraclePrice(tcapOracle);
price = totalMarketPrice.div(divisor);
}
/**
* @notice Returns the minimal required collateral to mint TCAP token
* @param _amount uint amount to mint
* @return collateral of the TCAP Token
* @dev TCAP token is 18 decimals
* @dev C = ((P * A * r) / 100) / cp
* C = Required Collateral
* P = TCAP Token Price
* A = Amount to Mint
* cp = Collateral Price
* r = Minimun Ratio for Liquidation
* Is only divided by 100 as eth price comes in wei to cancel the additional 0s
*/
function requiredCollateral(uint256 _amount)
public
view
virtual
returns (uint256 collateral)
{
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
collateral = ((tcapPrice.mul(_amount).mul(ratio)).div(100)).div(
collateralPrice
);
}
/**
* @notice Returns the minimal required TCAP to liquidate a Vault
* @param _vaultId of the vault to liquidate
* @return amount required of the TCAP Token
* @dev LT = ((((D * r) / 100) - cTcap) * 100) / (r - (p + 100))
* cTcap = ((C * cp) / P)
* LT = Required TCAP
* D = Vault Debt
* C = Required Collateral
* P = TCAP Token Price
* cp = Collateral Price
* r = Min Vault Ratio
* p = Liquidation Penalty
*/
function requiredLiquidationTCAP(uint256 _vaultId)
public
view
virtual
returns (uint256 amount)
{
Vault memory vault = vaults[_vaultId];
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
uint256 collateralTcap =
(vault.Collateral.mul(collateralPrice)).div(tcapPrice);
uint256 reqDividend =
(((vault.Debt.mul(ratio)).div(100)).sub(collateralTcap)).mul(100);
uint256 reqDivisor = ratio.sub(liquidationPenalty.add(100));
amount = reqDividend.div(reqDivisor);
}
/**
* @notice Returns the Reward for liquidating a vault
* @param _vaultId of the vault to liquidate
* @return rewardCollateral for liquidating Vault
* @dev the returned value is returned as collateral currency
* @dev R = (LT * (p + 100)) / 100
* R = Liquidation Reward
* LT = Required Liquidation TCAP
* p = liquidation penalty
*/
function liquidationReward(uint256 _vaultId)
public
view
virtual
returns (uint256 rewardCollateral)
{
uint256 req = requiredLiquidationTCAP(_vaultId);
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
uint256 reward = (req.mul(liquidationPenalty.add(100)));
rewardCollateral = (reward.mul(tcapPrice)).div(collateralPrice.mul(100));
}
/**
* @notice Returns the Collateral Ratio of the Vault
* @param _vaultId id of vault
* @return currentRatio
* @dev vr = (cp * (C * 100)) / D * P
* vr = Vault Ratio
* C = Vault Collateral
* cp = Collateral Price
* D = Vault Debt
* P = TCAP Token Price
*/
function getVaultRatio(uint256 _vaultId)
public
view
virtual
returns (uint256 currentRatio)
{
Vault memory vault = vaults[_vaultId];
if (vault.Id == 0 || vault.Debt == 0) {
currentRatio = 0;
} else {
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
currentRatio = (
(collateralPrice.mul(vault.Collateral.mul(100))).div(
vault.Debt.mul(TCAPPrice())
)
);
}
}
/**
* @notice Returns the required fee of ETH to burn the TCAP tokens
* @param _amount to burn
* @return fee
* @dev The returned value is returned in wei
* @dev f = (((P * A * b)/ 100))/ EP
* f = Burn Fee Value
* P = TCAP Token Price
* A = Amount to Burn
* b = Burn Fee %
* EP = ETH Price
*/
function getFee(uint256 _amount) public view virtual returns (uint256 fee) {
uint256 ethPrice = getOraclePrice(ETHPriceOracle);
fee = (TCAPPrice().mul(_amount).mul(burnFee)).div(100).div(ethPrice);
}
/**
* @notice Burns an amount of TCAP Tokens
* @param _vaultId vault id
* @param _amount to burn
*/
function _burn(uint256 _vaultId, uint256 _amount) internal {
Vault storage vault = vaults[_vaultId];
require(
vault.Debt >= _amount,
"VaultHandler::burn: amount greater than debt"
);
vault.Debt = vault.Debt.sub(_amount);
TCAPToken.burn(msg.sender, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/ERC165Checker.sol";
import "./IVaultHandler.sol";
import "./TCAP.sol";
import "./oracles/ChainlinkOracle.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title TCAP Orchestrator
* @author Cryptex.finance
* @notice Orchestrator contract in charge of managing the settings of the vaults, rewards and TCAP token. It acts as the owner of these contracts.
*/
contract Orchestrator is Ownable {
/// @dev Enum which saves the available functions to emergency call.
enum Functions {BURNFEE, LIQUIDATION, PAUSE}
/// @notice Address that can set to 0 the fees or pause the vaults in an emergency event
address public guardian;
/** @dev Interface constants*/
bytes4 private constant _INTERFACE_ID_IVAULT = 0x9e75ab0c;
bytes4 private constant _INTERFACE_ID_TCAP = 0xbd115939;
bytes4 private constant _INTERFACE_ID_CHAINLINK_ORACLE = 0x85be402b;
/// @dev tracks which vault was emergency called
mapping(IVaultHandler => mapping(Functions => bool)) private emergencyCalled;
/// @notice An event emitted when the guardian is updated
event GuardianSet(address indexed _owner, address guardian);
/// @notice An event emitted when a transaction is executed
event TransactionExecuted(
address indexed target,
uint256 value,
string signature,
bytes data
);
/**
* @notice Constructor
* @param _guardian The guardian address
*/
constructor(address _guardian) {
require(
_guardian != address(0),
"Orchestrator::constructor: guardian can't be zero"
);
guardian = _guardian;
}
/// @notice Throws if called by any account other than the guardian
modifier onlyGuardian() {
require(
msg.sender == guardian,
"Orchestrator::onlyGuardian: caller is not the guardian"
);
_;
}
/**
* @notice Throws if vault is not valid.
* @param _vault address
*/
modifier validVault(IVaultHandler _vault) {
require(
ERC165Checker.supportsInterface(address(_vault), _INTERFACE_ID_IVAULT),
"Orchestrator::validVault: not a valid vault"
);
_;
}
/**
* @notice Throws if TCAP Token is not valid
* @param _tcap address
*/
modifier validTCAP(TCAP _tcap) {
require(
ERC165Checker.supportsInterface(address(_tcap), _INTERFACE_ID_TCAP),
"Orchestrator::validTCAP: not a valid TCAP ERC20"
);
_;
}
/**
* @notice Throws if Chainlink Oracle is not valid
* @param _oracle address
*/
modifier validChainlinkOracle(address _oracle) {
require(
ERC165Checker.supportsInterface(
address(_oracle),
_INTERFACE_ID_CHAINLINK_ORACLE
),
"Orchestrator::validChainlinkOrchestrator: not a valid Chainlink Oracle"
);
_;
}
/**
* @notice Sets the guardian of the orchestrator
* @param _guardian address of the guardian
* @dev Only owner can call it
*/
function setGuardian(address _guardian) external onlyOwner {
require(
_guardian != address(0),
"Orchestrator::setGuardian: guardian can't be zero"
);
guardian = _guardian;
emit GuardianSet(msg.sender, _guardian);
}
/**
* @notice Sets the ratio of a vault
* @param _vault address
* @param _ratio value
* @dev Only owner can call it
*/
function setRatio(IVaultHandler _vault, uint256 _ratio)
external
onlyOwner
validVault(_vault)
{
_vault.setRatio(_ratio);
}
/**
* @notice Sets the burn fee of a vault
* @param _vault address
* @param _burnFee value
* @dev Only owner can call it
*/
function setBurnFee(IVaultHandler _vault, uint256 _burnFee)
external
onlyOwner
validVault(_vault)
{
_vault.setBurnFee(_burnFee);
}
/**
* @notice Sets the burn fee to 0, only used on a black swan event
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function setEmergencyBurnFee(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
require(
emergencyCalled[_vault][Functions.BURNFEE] != true,
"Orchestrator::setEmergencyBurnFee: emergency call already used"
);
emergencyCalled[_vault][Functions.BURNFEE] = true;
_vault.setBurnFee(0);
}
/**
* @notice Sets the liquidation penalty of a vault
* @param _vault address
* @param _liquidationPenalty value
* @dev Only owner can call it
*/
function setLiquidationPenalty(
IVaultHandler _vault,
uint256 _liquidationPenalty
) external onlyOwner validVault(_vault) {
_vault.setLiquidationPenalty(_liquidationPenalty);
}
/**
* @notice Sets the liquidation penalty of a vault to 0, only used on a black swan event
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function setEmergencyLiquidationPenalty(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
require(
emergencyCalled[_vault][Functions.LIQUIDATION] != true,
"Orchestrator::setEmergencyLiquidationPenalty: emergency call already used"
);
emergencyCalled[_vault][Functions.LIQUIDATION] = true;
_vault.setLiquidationPenalty(0);
}
/**
* @notice Pauses the Vault
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function pauseVault(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
require(
emergencyCalled[_vault][Functions.PAUSE] != true,
"Orchestrator::pauseVault: emergency call already used"
);
emergencyCalled[_vault][Functions.PAUSE] = true;
_vault.pause();
}
/**
* @notice Unpauses the Vault
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function unpauseVault(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
_vault.unpause();
}
/**
* @notice Enables or disables the TCAP Cap
* @param _tcap address
* @param _enable bool
* @dev Only owner can call it
* @dev Validates if _tcap is valid
*/
function enableTCAPCap(TCAP _tcap, bool _enable)
external
onlyOwner
validTCAP(_tcap)
{
_tcap.enableCap(_enable);
}
/**
* @notice Sets the TCAP maximum minting value
* @param _tcap address
* @param _cap uint value
* @dev Only owner can call it
* @dev Validates if _tcap is valid
*/
function setTCAPCap(TCAP _tcap, uint256 _cap)
external
onlyOwner
validTCAP(_tcap)
{
_tcap.setCap(_cap);
}
/**
* @notice Adds Vault to TCAP ERC20
* @param _tcap address
* @param _vault address
* @dev Only owner can call it
* @dev Validates if _tcap is valid
* @dev Validates if _vault is valid
*/
function addTCAPVault(TCAP _tcap, IVaultHandler _vault)
external
onlyOwner
validTCAP(_tcap)
validVault(_vault)
{
_tcap.addVaultHandler(address(_vault));
}
/**
* @notice Removes Vault to TCAP ERC20
* @param _tcap address
* @param _vault address
* @dev Only owner can call it
* @dev Validates if _tcap is valid
* @dev Validates if _vault is valid
*/
function removeTCAPVault(TCAP _tcap, IVaultHandler _vault)
external
onlyOwner
validTCAP(_tcap)
validVault(_vault)
{
_tcap.removeVaultHandler(address(_vault));
}
/**
* @notice Allows the owner to execute custom transactions
* @param target address
* @param value uint256
* @param signature string
* @param data bytes
* @dev Only owner can call it
*/
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data
) external payable onlyOwner returns (bytes memory) {
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
require(
target != address(0),
"Orchestrator::executeTransaction: target can't be zero"
);
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) =
target.call{value: value}(callData);
require(
success,
"Orchestrator::executeTransaction: Transaction execution reverted."
);
emit TransactionExecuted(target, value, signature, data);
(target, value, signature, data);
return returnData;
}
/**
* @notice Retrieves the eth stuck on the orchestrator
* @param _to address
* @dev Only owner can call it
*/
function retrieveETH(address _to) external onlyOwner {
require(
_to != address(0),
"Orchestrator::retrieveETH: address can't be zero"
);
uint256 amount = address(this).balance;
payable(_to).transfer(amount);
}
/// @notice Allows the contract to receive ETH
receive() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./Orchestrator.sol";
/**
* @title Total Market Cap Token
* @author Cryptex.finance
* @notice ERC20 token on the Ethereum Blockchain that provides total exposure to the cryptocurrency sector.
*/
contract TCAP is ERC20, Ownable, IERC165 {
/// @notice Open Zeppelin libraries
using SafeMath for uint256;
/// @notice if enabled TCAP can't be minted if the total supply is above or equal the cap value
bool public capEnabled = false;
/// @notice Maximum value the total supply of TCAP
uint256 public cap;
/**
* @notice Address to Vault Handler
* @dev Only vault handlers can mint and burn TCAP
*/
mapping(address => bool) public vaultHandlers;
/**
* @dev the computed interface ID according to ERC-165. The interface ID is a XOR of interface method selectors.
* mint.selector ^
* burn.selector ^
* setCap.selector ^
* enableCap.selector ^
* transfer.selector ^
* transferFrom.selector ^
* addVaultHandler.selector ^
* removeVaultHandler.selector ^
* approve.selector => 0xbd115939
*/
bytes4 private constant _INTERFACE_ID_TCAP = 0xbd115939;
/// @dev bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/// @notice An event emitted when a vault handler is added
event VaultHandlerAdded(
address indexed _owner,
address indexed _tokenHandler
);
/// @notice An event emitted when a vault handler is removed
event VaultHandlerRemoved(
address indexed _owner,
address indexed _tokenHandler
);
/// @notice An event emitted when the cap value is updated
event NewCap(address indexed _owner, uint256 _amount);
/// @notice An event emitted when the cap is enabled or disabled
event NewCapEnabled(address indexed _owner, bool _enable);
/**
* @notice Constructor
* @param _name uint256
* @param _symbol uint256
* @param _cap uint256
* @param _orchestrator address
*/
constructor(
string memory _name,
string memory _symbol,
uint256 _cap,
Orchestrator _orchestrator
) ERC20(_name, _symbol) {
cap = _cap;
/// @dev transfer ownership to orchestrator
transferOwnership(address(_orchestrator));
}
/// @notice Reverts if called by any account that is not a vault.
modifier onlyVault() {
require(
vaultHandlers[msg.sender],
"TCAP::onlyVault: caller is not a vault"
);
_;
}
/**
* @notice Adds a new address as a vault
* @param _vaultHandler address of a contract with permissions to mint and burn tokens
* @dev Only owner can call it
*/
function addVaultHandler(address _vaultHandler) external onlyOwner {
vaultHandlers[_vaultHandler] = true;
emit VaultHandlerAdded(msg.sender, _vaultHandler);
}
/**
* @notice Removes an address as a vault
* @param _vaultHandler address of the contract to be removed as vault
* @dev Only owner can call it
*/
function removeVaultHandler(address _vaultHandler) external onlyOwner {
vaultHandlers[_vaultHandler] = false;
emit VaultHandlerRemoved(msg.sender, _vaultHandler);
}
/**
* @notice Mints TCAP Tokens
* @param _account address of the receiver of tokens
* @param _amount uint of tokens to mint
* @dev Only vault can call it
*/
function mint(address _account, uint256 _amount) external onlyVault {
_mint(_account, _amount);
}
/**
* @notice Burns TCAP Tokens
* @param _account address of the account which is burning tokens.
* @param _amount uint of tokens to burn
* @dev Only vault can call it
*/
function burn(address _account, uint256 _amount) external onlyVault {
_burn(_account, _amount);
}
/**
* @notice Sets maximum value the total supply of TCAP can have
* @param _cap value
* @dev When capEnabled is true, mint is not allowed to issue tokens that would increase the total supply above or equal the specified capacity.
* @dev Only owner can call it
*/
function setCap(uint256 _cap) external onlyOwner {
cap = _cap;
emit NewCap(msg.sender, _cap);
}
/**
* @notice Enables or Disables the Total Supply Cap.
* @param _enable value
* @dev When capEnabled is true, minting will not be allowed above the max capacity. It can exist a supply above the cap, but it prevents minting above the cap.
* @dev Only owner can call it
*/
function enableCap(bool _enable) external onlyOwner {
capEnabled = _enable;
emit NewCapEnabled(msg.sender, _enable);
}
/**
* @notice ERC165 Standard for support of interfaces
* @param _interfaceId bytes of interface
* @return bool
*/
function supportsInterface(bytes4 _interfaceId)
external
pure
override
returns (bool)
{
return (_interfaceId == _INTERFACE_ID_TCAP ||
_interfaceId == _INTERFACE_ID_ERC165);
}
/**
* @notice executes before each token transfer or mint
* @param _from address
* @param _to address
* @param _amount value to transfer
* @dev See {ERC20-_beforeTokenTransfer}.
* @dev minted tokens must not cause the total supply to go over the cap.
* @dev Reverts if the to address is equal to token address
*/
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _amount
) internal virtual override {
super._beforeTokenTransfer(_from, _to, _amount);
require(
_to != address(this),
"TCAP::transfer: can't transfer to TCAP contract"
);
if (_from == address(0) && capEnabled) {
// When minting tokens
require(
totalSupply().add(_amount) <= cap,
"TCAP::Transfer: TCAP cap exceeded"
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
/**
* @title Chainlink Oracle
* @author Cryptex.finance
* @notice Contract in charge or reading the information from a Chainlink Oracle. TCAP contracts read the price directly from this contract. More information can be found on Chainlink Documentation
*/
contract ChainlinkOracle is Ownable, IERC165 {
AggregatorV3Interface internal aggregatorContract;
/*
* setReferenceContract.selector ^
* getLatestAnswer.selector ^
* getLatestTimestamp.selector ^
* getPreviousAnswer.selector ^
* getPreviousTimestamp.selector => 0x85be402b
*/
bytes4 private constant _INTERFACE_ID_CHAINLINK_ORACLE = 0x85be402b;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @notice Called once the contract is deployed.
* Set the Chainlink Oracle as an aggregator.
*/
constructor(address _aggregator, address _timelock) {
require(_aggregator != address(0) && _timelock != address(0), "address can't be 0");
aggregatorContract = AggregatorV3Interface(_aggregator);
transferOwnership(_timelock);
}
/**
* @notice Changes the reference contract.
* @dev Only owner can call it.
*/
function setReferenceContract(address _aggregator) public onlyOwner() {
aggregatorContract = AggregatorV3Interface(_aggregator);
}
/**
* @notice Returns the latest answer from the reference contract.
* @return price
*/
function getLatestAnswer() public view returns (int256) {
(
uint80 roundID,
int256 price,
,
uint256 timeStamp,
uint80 answeredInRound
) = aggregatorContract.latestRoundData();
require(
timeStamp != 0,
"ChainlinkOracle::getLatestAnswer: round is not complete"
);
require(
answeredInRound >= roundID,
"ChainlinkOracle::getLatestAnswer: stale data"
);
return price;
}
/**
* @notice Returns the latest round from the reference contract.
*/
function getLatestRound()
public
view
returns (
uint80,
int256,
uint256,
uint256,
uint80
)
{
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = aggregatorContract.latestRoundData();
return (roundID, price, startedAt, timeStamp, answeredInRound);
}
/**
* @notice Returns a given round from the reference contract.
* @param _id of round
*/
function getRound(uint80 _id)
public
view
returns (
uint80,
int256,
uint256,
uint256,
uint80
)
{
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = aggregatorContract.getRoundData(_id);
return (roundID, price, startedAt, timeStamp, answeredInRound);
}
/**
* @notice Returns the last time the Oracle was updated.
*/
function getLatestTimestamp() public view returns (uint256) {
(, , , uint256 timeStamp, ) = aggregatorContract.latestRoundData();
return timeStamp;
}
/**
* @notice Returns a previous answer updated on the Oracle.
* @param _id of round
* @return price
*/
function getPreviousAnswer(uint80 _id) public view returns (int256) {
(uint80 roundID, int256 price, , , ) = aggregatorContract.getRoundData(_id);
require(
_id <= roundID,
"ChainlinkOracle::getPreviousAnswer: not enough history"
);
return price;
}
/**
* @notice Returns a previous time the Oracle was updated.
* @param _id of round
* @return timeStamp
*/
function getPreviousTimestamp(uint80 _id) public view returns (uint256) {
(uint80 roundID, , , uint256 timeStamp, ) =
aggregatorContract.getRoundData(_id);
require(
_id <= roundID,
"ChainlinkOracle::getPreviousTimestamp: not enough history"
);
return timeStamp;
}
/**
* @notice ERC165 Standard for support of interfaces.
*/
function supportsInterface(bytes4 interfaceId)
external
pure
override
returns (bool)
{
return (interfaceId == _INTERFACE_ID_CHAINLINK_ORACLE ||
interfaceId == _INTERFACE_ID_ERC165);
}
} | * @notice Sets the liquidation penalty % charged on liquidation @param _liquidationPenalty uint @dev Only owner can call it @dev recommended value is between 1-15% and can't be above 100%/ | function setLiquidationPenalty(uint256 _liquidationPenalty)
external
virtual
onlyOwner
{
require(
_liquidationPenalty.add(100) < ratio,
"VaultHandler::setLiquidationPenalty: liquidation penalty too high"
);
liquidationPenalty = _liquidationPenalty;
emit NewLiquidationPenalty(msg.sender, _liquidationPenalty);
}
| 172,355 | [
1,
2785,
326,
4501,
26595,
367,
23862,
738,
1149,
2423,
603,
4501,
26595,
367,
225,
389,
549,
26595,
367,
24251,
15006,
2254,
225,
5098,
3410,
848,
745,
518,
225,
14553,
460,
353,
3086,
404,
17,
3600,
9,
471,
848,
1404,
506,
5721,
2130,
9,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
444,
48,
18988,
350,
367,
24251,
15006,
12,
11890,
5034,
389,
549,
26595,
367,
24251,
15006,
13,
203,
565,
3903,
203,
565,
5024,
203,
565,
1338,
5541,
203,
225,
288,
203,
565,
2583,
12,
203,
1377,
389,
549,
26595,
367,
24251,
15006,
18,
1289,
12,
6625,
13,
411,
7169,
16,
203,
1377,
315,
12003,
1503,
2866,
542,
48,
18988,
350,
367,
24251,
15006,
30,
4501,
26595,
367,
23862,
4885,
3551,
6,
203,
565,
11272,
203,
203,
565,
4501,
26595,
367,
24251,
15006,
273,
389,
549,
26595,
367,
24251,
15006,
31,
203,
565,
3626,
1166,
48,
18988,
350,
367,
24251,
15006,
12,
3576,
18,
15330,
16,
389,
549,
26595,
367,
24251,
15006,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-09-28
*/
// Sources flattened with hardhat v2.1.2 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File contracts/TokensFarm.sol
pragma solidity 0.6.12;
contract TokensFarm is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
enum EarlyWithdrawPenalty {
NO_PENALTY,
BURN_REWARDS,
REDISTRIBUTE_REWARDS
}
// Info of each user.
struct StakeInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 depositTime; // Time when user deposited.
}
IERC20 public tokenStaked; // Address of ERC20 token contract.
uint256 public lastRewardTime; // Last time number that ERC20s distribution occurs.
uint256 public accERC20PerShare; // Accumulated ERC20s per share, times 1e18.
uint256 public totalDeposits; // Total tokens deposited in the farm.
// If contractor allows early withdraw on stakes
bool public isEarlyWithdrawAllowed;
// Minimal period of time to stake
uint256 public minTimeToStake;
// Address of the ERC20 Token contract.
IERC20 public erc20;
// The total amount of ERC20 that's paid out as reward.
uint256 public paidOut;
// ERC20 tokens rewarded per second.
uint256 public rewardPerSecond;
// Total rewards added to farm
uint256 public totalRewards;
// Info of each user that stakes ERC20 tokens.
mapping(address => StakeInfo[]) public stakeInfo;
// The time when farming starts.
uint256 public startTime;
// The time when farming ends.
uint256 public endTime;
// Early withdraw penalty
EarlyWithdrawPenalty public penalty;
// Counter for funding
uint256 fundCounter;
// Congress address
address public congressAddress;
// Stake fee percent
uint256 public stakeFeePercent;
// Reward fee percent
uint256 public rewardFeePercent;
// Fee collector address
address payable public feeCollector;
// Flat fee amount
uint256 public flatFeeAmount;
// Fee option
bool public isFlatFeeAllowed;
// Events
event Deposit(address indexed user, uint256 stakeId, uint256 amount);
event Withdraw(address indexed user, uint256 stakeId, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 stakeId,
uint256 amount
);
event EarlyWithdrawPenaltyChange(EarlyWithdrawPenalty penalty);
modifier validateStakeByStakeId(address _user, uint256 stakeId) {
require(stakeId < stakeInfo[_user].length, "Stake does not exist");
_;
}
constructor(
IERC20 _erc20,
uint256 _rewardPerSecond,
uint256 _startTime,
uint256 _minTimeToStake,
bool _isEarlyWithdrawAllowed,
EarlyWithdrawPenalty _penalty,
IERC20 _tokenStaked,
address _congressAddress,
uint256 _stakeFeePercent,
uint256 _rewardFeePercent,
uint256 _flatFeeAmount,
address payable _feeCollector,
bool _isFlatFeeAllowed
) public {
require(address(_erc20) != address(0x0), "Wrong token address.");
require(_rewardPerSecond > 0, "Rewards per second must be > 0.");
require(
_startTime >= block.timestamp,
"Start timne can not be in the past."
);
require(_stakeFeePercent < 100, "Stake fee must be < 100.");
require(_rewardFeePercent < 100, "Reward fee must be < 100.");
require(_feeCollector != address(0x0), "Wrong fee collector address.");
require(
_congressAddress != address(0x0),
"Congress address can not be 0."
);
erc20 = _erc20;
rewardPerSecond = _rewardPerSecond;
startTime = _startTime;
endTime = _startTime;
minTimeToStake = _minTimeToStake;
isEarlyWithdrawAllowed = _isEarlyWithdrawAllowed;
congressAddress = _congressAddress;
stakeFeePercent = _stakeFeePercent;
rewardFeePercent = _rewardFeePercent;
flatFeeAmount = _flatFeeAmount;
feeCollector = _feeCollector;
isFlatFeeAllowed = _isFlatFeeAllowed;
_setEarlyWithdrawPenalty(_penalty);
_addPool(_tokenStaked);
}
// Set minimun time to stake
function setMinTimeToStake(uint256 _minTimeToStake) external onlyOwner {
minTimeToStake = _minTimeToStake;
}
// Set fee collector address
function setFeeCollector(address payable _feeCollector) external onlyOwner {
require(_feeCollector != address(0x0), "Wrong fee collector address.");
feeCollector = _feeCollector;
}
// Set early withdrawal penalty, if applicable
function _setEarlyWithdrawPenalty(EarlyWithdrawPenalty _penalty) internal {
penalty = _penalty;
emit EarlyWithdrawPenaltyChange(penalty);
}
// Fund the farm, increase the end time
function fund(uint256 _amount) external {
fundCounter = fundCounter.add(1);
_fundInternal(_amount);
erc20.safeTransferFrom(address(msg.sender), address(this), _amount);
if (fundCounter == 2) {
transferOwnership(congressAddress);
}
}
// Internally fund the farm by adding farmed rewards by user to the end
function _fundInternal(uint256 _amount) internal {
require(
block.timestamp < endTime,
"fund: too late, the farm is closed"
);
require(_amount > 0, "Amount must be greater than 0.");
// Compute new end time
endTime += _amount.div(rewardPerSecond);
// Increase farm total rewards
totalRewards = totalRewards.add(_amount);
}
// Add a new ERC20 token to the pool. Can only be called by the owner.
function _addPool(IERC20 _tokenStaked) internal {
require(
address(_tokenStaked) != address(0x0),
"Must input valid address."
);
require(
address(tokenStaked) == address(0x0),
"Pool can be set only once."
);
uint256 _lastRewardTime = block.timestamp > startTime
? block.timestamp
: startTime;
tokenStaked = _tokenStaked;
lastRewardTime = _lastRewardTime;
accERC20PerShare = 0;
totalDeposits = 0;
}
// View function to see deposited ERC20 token for a user.
function deposited(address _user, uint256 stakeId)
public
view
validateStakeByStakeId(_user, stakeId)
returns (uint256)
{
StakeInfo storage stake = stakeInfo[_user][stakeId];
return stake.amount;
}
// View function to see pending ERC20s for a user.
function pending(address _user, uint256 stakeId)
public
view
validateStakeByStakeId(_user, stakeId)
returns (uint256)
{
StakeInfo storage stake = stakeInfo[_user][stakeId];
if (stake.amount == 0) {
return 0;
}
uint256 _accERC20PerShare = accERC20PerShare;
uint256 tokenSupply = totalDeposits;
if (block.timestamp > lastRewardTime && tokenSupply != 0) {
uint256 lastTime = block.timestamp < endTime
? block.timestamp
: endTime;
uint256 timeToCompare = lastRewardTime < endTime
? lastRewardTime
: endTime;
uint256 nrOfSeconds = lastTime.sub(timeToCompare);
uint256 erc20Reward = nrOfSeconds.mul(rewardPerSecond);
_accERC20PerShare = _accERC20PerShare.add(
erc20Reward.mul(1e18).div(tokenSupply)
);
}
return
stake.amount.mul(_accERC20PerShare).div(1e18).sub(stake.rewardDebt);
}
// View function to see deposit timestamp for a user.
function depositTimestamp(address _user, uint256 stakeId)
public
view
validateStakeByStakeId(_user, stakeId)
returns (uint256)
{
StakeInfo storage stake = stakeInfo[_user][stakeId];
return stake.depositTime;
}
// View function for total reward the farm has yet to pay out.
function totalPending() external view returns (uint256) {
if (block.timestamp <= startTime) {
return 0;
}
uint256 lastTime = block.timestamp < endTime
? block.timestamp
: endTime;
return rewardPerSecond.mul(lastTime - startTime).sub(paidOut);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool() public {
uint256 lastTime = block.timestamp < endTime
? block.timestamp
: endTime;
if (lastTime <= lastRewardTime) {
return;
}
uint256 tokenSupply = totalDeposits;
if (tokenSupply == 0) {
lastRewardTime = lastTime;
return;
}
uint256 nrOfSeconds = lastTime.sub(lastRewardTime);
uint256 erc20Reward = nrOfSeconds.mul(rewardPerSecond);
accERC20PerShare = accERC20PerShare.add(
erc20Reward.mul(1e18).div(tokenSupply)
);
lastRewardTime = block.timestamp;
}
// Deposit ERC20 tokens to Farm for ERC20 allocation.
function deposit(uint256 _amount) external payable {
StakeInfo memory stake;
// Update pool
updatePool();
// Take token and transfer to contract
tokenStaked.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
uint256 stakedAmount = _amount;
if (isFlatFeeAllowed) {
// Collect flat fee
require(
msg.value >= flatFeeAmount,
"Payable amount is less than fee amount."
);
(bool sent, ) = payable(feeCollector).call{value: msg.value}("");
require(sent, "Failed to send flat fee");
} else if (stakeFeePercent > 0) { // Handle this case only if flat fee is not allowed, and stakeFeePercent > 0
// Compute the fee
uint256 feeAmount = _amount.mul(stakeFeePercent).div(100);
// Compute stake amount
stakedAmount = _amount.sub(feeAmount);
// Transfer fee to Fee Collector
tokenStaked.safeTransfer(feeCollector, feeAmount);
}
// Increase total deposits
totalDeposits = totalDeposits.add(stakedAmount);
// Update user accounting
stake.amount = stakedAmount;
stake.rewardDebt = stake.amount.mul(accERC20PerShare).div(1e18);
stake.depositTime = block.timestamp;
// Compute stake id
uint256 stakeId = stakeInfo[msg.sender].length;
// Push new stake to array of stakes for user
stakeInfo[msg.sender].push(stake);
// Emit deposit event
emit Deposit(msg.sender, stakeId, stakedAmount);
}
// Withdraw ERC20 tokens from Farm.
function withdraw(uint256 _amount, uint256 stakeId)
external
payable
nonReentrant
validateStakeByStakeId(msg.sender, stakeId)
{
bool minimalTimeStakeRespected;
StakeInfo storage stake = stakeInfo[msg.sender][stakeId];
require(
stake.amount >= _amount,
"withdraw: can't withdraw more than deposit"
);
updatePool();
minimalTimeStakeRespected = stake.depositTime.add(minTimeToStake) <= block.timestamp;
// if early withdraw is not allowed, user can't withdraw funds before
if (!isEarlyWithdrawAllowed) {
// Check if user has respected minimal time to stake, require it.
require(
minimalTimeStakeRespected,
"User can not withdraw funds yet."
);
}
// Compute pending rewards amount of user rewards
uint256 pendingAmount = stake
.amount
.mul(accERC20PerShare)
.div(1e18)
.sub(stake.rewardDebt);
// Penalties in case user didn't stake enough time
if (pendingAmount > 0) {
if (
penalty == EarlyWithdrawPenalty.BURN_REWARDS &&
!minimalTimeStakeRespected
) {
// Burn to address (1)
_erc20Transfer(address(1), pendingAmount);
} else if (
penalty == EarlyWithdrawPenalty.REDISTRIBUTE_REWARDS &&
!minimalTimeStakeRespected
) {
if (block.timestamp >= endTime) {
// Burn rewards because farm can not be funded anymore since it ended
_erc20Transfer(address(1), pendingAmount);
} else {
// Re-fund the farm
_fundInternal(pendingAmount);
}
} else {
// In case either there's no penalty
_erc20Transfer(msg.sender, pendingAmount);
}
}
stake.amount = stake.amount.sub(_amount);
stake.rewardDebt = stake.amount.mul(accERC20PerShare).div(1e18);
tokenStaked.safeTransfer(address(msg.sender), _amount);
totalDeposits = totalDeposits.sub(_amount);
// Emit Withdraw event
emit Withdraw(msg.sender, stakeId, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 stakeId)
external
nonReentrant
validateStakeByStakeId(msg.sender, stakeId)
{
StakeInfo storage stake = stakeInfo[msg.sender][stakeId];
// if early withdraw is not allowed, user can't withdraw funds before
if (!isEarlyWithdrawAllowed) {
bool minimalTimeStakeRespected = stake.depositTime.add(
minTimeToStake
) <= block.timestamp;
// Check if user has respected minimal time to stake, require it.
require(
minimalTimeStakeRespected,
"User can not withdraw funds yet."
);
}
tokenStaked.safeTransfer(address(msg.sender), stake.amount);
totalDeposits = totalDeposits.sub(stake.amount);
emit EmergencyWithdraw(msg.sender, stakeId, stake.amount);
stake.amount = 0;
stake.rewardDebt = 0;
}
// Get number of stakes user has
function getNumberOfUserStakes(address user)
external
view
returns (uint256)
{
return stakeInfo[user].length;
}
// Get user pending amounts, stakes and deposit time
function getUserStakesAndPendingAmounts(address user)
external
view
returns (
uint256[] memory,
uint256[] memory,
uint256[] memory
)
{
uint256 numberOfStakes = stakeInfo[user].length;
uint256[] memory deposits = new uint256[](numberOfStakes);
uint256[] memory pendingAmounts = new uint256[](numberOfStakes);
uint256[] memory depositTime = new uint256[](numberOfStakes);
for (uint256 i = 0; i < numberOfStakes; i++) {
deposits[i] = deposited(user, i);
pendingAmounts[i] = pending(user, i);
depositTime[i] = depositTimestamp(user, i);
}
return (deposits, pendingAmounts, depositTime);
}
// Get total rewards locked/unlocked
function getTotalRewardsLockedUnlocked()
external
view
returns (uint256, uint256)
{
uint256 totalRewardsLocked;
uint256 totalRewardsUnlocked;
if (block.timestamp <= startTime) {
totalRewardsUnlocked = 0;
totalRewardsLocked = totalRewards;
} else {
uint256 lastTime = block.timestamp < endTime
? block.timestamp
: endTime;
totalRewardsUnlocked = rewardPerSecond.mul(lastTime - startTime);
totalRewardsLocked = totalRewards - totalRewardsUnlocked;
}
return (totalRewardsUnlocked, totalRewardsLocked);
}
// Transfer ERC20 and update the required ERC20 to payout all rewards
function _erc20Transfer(address _to, uint256 _amount) internal {
if (isFlatFeeAllowed) {
// Collect flat fee
require(
msg.value >= flatFeeAmount,
"Payable amount is less than fee amount."
);
(bool sent, ) = payable(feeCollector).call{value: msg.value}("");
require(sent, "Failed to end flat fee");
// send reward
erc20.transfer(_to, _amount);
paidOut += _amount;
} else if (stakeFeePercent > 0) {
// Collect reward fee
uint256 feeAmount = _amount.mul(rewardFeePercent).div(100);
uint256 rewardAmount = _amount.sub(feeAmount);
erc20.transfer(feeCollector, feeAmount);
// send reward
erc20.transfer(_to, rewardAmount);
paidOut += _amount;
} else {
erc20.transfer(_to, _amount);
paidOut += _amount;
}
}
} | Withdraw without caring about rewards. EMERGENCY ONLY. if early withdraw is not allowed, user can't withdraw funds before Check if user has respected minimal time to stake, require it. | function emergencyWithdraw(uint256 stakeId)
external
nonReentrant
validateStakeByStakeId(msg.sender, stakeId)
{
StakeInfo storage stake = stakeInfo[msg.sender][stakeId];
if (!isEarlyWithdrawAllowed) {
bool minimalTimeStakeRespected = stake.depositTime.add(
minTimeToStake
) <= block.timestamp;
require(
minimalTimeStakeRespected,
"User can not withdraw funds yet."
);
}
tokenStaked.safeTransfer(address(msg.sender), stake.amount);
totalDeposits = totalDeposits.sub(stake.amount);
emit EmergencyWithdraw(msg.sender, stakeId, stake.amount);
stake.amount = 0;
stake.rewardDebt = 0;
}
| 10,509,136 | [
1,
1190,
9446,
2887,
5926,
310,
2973,
283,
6397,
18,
7141,
654,
16652,
16068,
20747,
18,
309,
11646,
598,
9446,
353,
486,
2935,
16,
729,
848,
1404,
598,
9446,
284,
19156,
1865,
2073,
309,
729,
711,
400,
1789,
16745,
813,
358,
384,
911,
16,
2583,
518,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
801,
24530,
1190,
9446,
12,
11890,
5034,
384,
911,
548,
13,
203,
3639,
3903,
203,
3639,
1661,
426,
8230,
970,
203,
3639,
1954,
510,
911,
858,
510,
911,
548,
12,
3576,
18,
15330,
16,
384,
911,
548,
13,
203,
565,
288,
203,
3639,
934,
911,
966,
2502,
384,
911,
273,
384,
911,
966,
63,
3576,
18,
15330,
6362,
334,
911,
548,
15533,
203,
203,
3639,
309,
16051,
291,
41,
20279,
1190,
9446,
5042,
13,
288,
203,
5411,
1426,
16745,
950,
510,
911,
607,
1789,
273,
384,
911,
18,
323,
1724,
950,
18,
1289,
12,
203,
7734,
1131,
950,
774,
510,
911,
203,
5411,
262,
1648,
1203,
18,
5508,
31,
203,
5411,
2583,
12,
203,
7734,
16745,
950,
510,
911,
607,
1789,
16,
203,
7734,
315,
1299,
848,
486,
598,
9446,
284,
19156,
4671,
1199,
203,
5411,
11272,
203,
3639,
289,
203,
203,
3639,
1147,
510,
9477,
18,
4626,
5912,
12,
2867,
12,
3576,
18,
15330,
3631,
384,
911,
18,
8949,
1769,
203,
3639,
2078,
758,
917,
1282,
273,
2078,
758,
917,
1282,
18,
1717,
12,
334,
911,
18,
8949,
1769,
203,
203,
3639,
3626,
512,
6592,
75,
2075,
1190,
9446,
12,
3576,
18,
15330,
16,
384,
911,
548,
16,
384,
911,
18,
8949,
1769,
203,
203,
3639,
384,
911,
18,
8949,
273,
374,
31,
203,
3639,
384,
911,
18,
266,
2913,
758,
23602,
273,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract OGCATS is ERC721Enumerable, Ownable, ReentrancyGuard {
using Address for address;
using Strings for uint256;
using Counters for Counters.Counter;
using MerkleProof for bytes32[];
/**
* @notice Input data root, Merkle tree root for an array of (address, tokenId) pairs,
* available for minting
*/
bytes32 public root = 0x53f1995dc0ddf5a8ff7b345d7a2e822cad528e6d5a7afcae13e6cf7a050e03b4;
string public _contractBaseURI = "https://api.ogcats.io/metadata/";
string public _contractURI = "https://to.wtf/contract_uri/ogcats/contract_uri.json";
uint256 public tokenPrice = 0.05 ether;
mapping(address => uint256) public usedAddresses; //max 3 per address for whitelist
bool public locked; //baseURI & contractURI lock
uint256 public maxSupply = 6000;
uint256 public maxSupplyPresale = 1000;
uint256 public whitelistStartTime = 1639152000;
uint256 public publicSaleStartTime = 1639238400;
Counters.Counter private _tokenIds;
constructor() ERC721("OGCATS", "OGCT") {}
//whitelistBuy can buy. max 3 tokens per whitelisted address
function whitelistBuy(
uint256 qty,
uint256 tokenId,
bytes32[] calldata proof
) external payable nonReentrant {
require(tokenPrice * qty == msg.value, "exact amount needed");
require(usedAddresses[msg.sender] + qty <= 3, "max 3 per wallet");
require(_tokenIds.current() + qty <= maxSupplyPresale, "out of stock");
require(block.timestamp >= whitelistStartTime, "not live");
require(isTokenValid(msg.sender, tokenId, proof), "invalid proof");
usedAddresses[msg.sender] += qty;
for (uint256 i = 0; i < qty; i++) {
_tokenIds.increment();
_safeMint(msg.sender, _tokenIds.current());
}
}
//regular public sale
function buy(uint256 qty) external payable {
require(tokenPrice * qty == msg.value, "exact amount needed");
require(qty <= 5, "max 5 at once");
require(_tokenIds.current() + qty <= maxSupply, "out of stock");
require(block.timestamp >= publicSaleStartTime, "not live");
for (uint256 i = 0; i < qty; i++) {
_tokenIds.increment();
_safeMint(msg.sender, _tokenIds.current());
}
}
function isTokenValid(
address _to,
uint256 _tokenId,
bytes32[] memory _proof
) public view returns (bool) {
// construct Merkle tree leaf from the inputs supplied
bytes32 leaf = keccak256(abi.encodePacked(_to, _tokenId));
// verify the proof supplied, and return the verification result
return _proof.verify(root, leaf);
}
function setMerkleRoot(bytes32 _root) external onlyOwner {
root = _root;
}
// admin can mint them for giveaways, airdrops etc
function adminMint(uint256 qty, address to) external onlyOwner {
require(qty <= 25, "no more than 25");
require(_tokenIds.current() + qty <= maxSupply, "out of stock");
for (uint256 i = 0; i < qty; i++) {
_tokenIds.increment();
_safeMint(to, _tokenIds.current());
}
}
//----------------------------------
//----------- other code -----------
//----------------------------------
function tokensOfOwner(address _owner) external view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
function exists(uint256 _tokenId) external view returns (bool) {
return _exists(_tokenId);
}
function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) {
return _isApprovedOrOwner(_spender, _tokenId);
}
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(_contractBaseURI, _tokenId.toString(), ".json"));
}
function setBaseURI(string memory newBaseURI) external onlyOwner {
require(!locked, "locked functions");
_contractBaseURI = newBaseURI;
}
function setContractURI(string memory newuri) external onlyOwner {
require(!locked, "locked functions");
_contractURI = newuri;
}
function contractURI() public view returns (string memory) {
return _contractURI;
}
function reclaimERC20(IERC20 erc20Token) external onlyOwner {
erc20Token.transfer(msg.sender, erc20Token.balanceOf(address(this)));
}
function reclaimERC721(IERC721 erc721Token, uint256 id) external onlyOwner {
erc721Token.safeTransferFrom(address(this), msg.sender, id);
}
function reclaimERC1155(
IERC1155 erc1155Token,
uint256 id,
uint256 amount
) external onlyOwner {
erc1155Token.safeTransferFrom(address(this), msg.sender, id, amount, "");
}
//in unix
function setWhitelistStartTime(uint256 newTime) external onlyOwner {
whitelistStartTime = newTime;
}
//in unix
function setPublicSaleStartTime(uint256 newTime) external onlyOwner {
publicSaleStartTime = newTime;
}
function changePricePerToken(uint256 newPrice) external onlyOwner {
tokenPrice = newPrice;
}
function decreaseMaxSupply(uint256 newMaxSupply) external onlyOwner {
require(newMaxSupply < maxSupply, "decrease only");
maxSupply = newMaxSupply;
}
// and for the eternity!
function lockBaseURIandContractURI() external onlyOwner {
locked = true;
}
// earnings withdrawal
function withdrawEarnings() public onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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
// OpenZeppelin Contracts v4.4.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 `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/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;
}
} | baseURI & contractURI lock
| bool public locked; | 1,394,924 | [
1,
1969,
3098,
473,
6835,
3098,
2176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
6430,
1071,
8586,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.6;
import "./FlightSuretyData.sol";
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
contract FlightSuretyApp is Ownable {
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
bool private operational = true;
FlightSuretyData private dataContract;
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(bytes32 => Flight) private flights;
// Needs to be a mapping to make sure an airline cannot vote twice
mapping(address => mapping(address => bool)) private airlines;
mapping(address => uint8) private airlineVotes;
uint256 private totalNumberAirlines = 1; // We always start with one airline registered
event InsuranceClaimPaid(address);
event FlightRegistered(string flight, uint256 timestamp, address airline);
event AirlineRegistered(address airline);
event AirlinePreRegistered(address airline, uint8 votes);
event InsuranceBought(address airline, string flightName, uint256 flightTime, address customer, uint256 amount);
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational() {
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires that the caller is an airline
*/
modifier requireAirline() {
require(dataContract.isAirline(msg.sender), "Not an airline");
_;
}
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
*
* Takes the address of the dataContract and registers it
*/
constructor (address payable _dataContract) {
dataContract = FlightSuretyData(_dataContract);
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function isOperational() public view returns(bool) {
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus(bool mode) external onlyOwner {
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
*
*/
function registerAirline(address airline) external requireIsOperational requireAirline
returns(bool success, uint256 votes) {
// Up to the 4th registered airline can be registered by a sole airline
if (totalNumberAirlines < 4) {
_registerAirline(airline);
return (true, 1);
}
// 5th and subsequent airline need 50% of the votes of all registered airlines
if (!airlines[airline][msg.sender]) { // This airline has not voted yet
airlines[airline][msg.sender] = true; // Voted
airlineVotes[airline]++;
if (airlineVotes[airline] > totalNumberAirlines / 2) {
_registerAirline(airline);
return (true, airlineVotes[airline]);
}
}
emit AirlinePreRegistered(airline, airlineVotes[airline]);
return (false, airlineVotes[airline]);
}
function _registerAirline(address airline) internal {
dataContract.registerAirline(airline);
totalNumberAirlines++;
emit AirlineRegistered(airline);
}
/**
* @dev Register a future flight for insuring.
*
* @param flightName codenumber of the flight
* @param flightTime time of the flight
*
* The sender should be the airline registering the flight
*/
function registerFlight(string memory flightName, uint256 flightTime) external requireIsOperational {
require(dataContract.isAirline(msg.sender), "Only an airline can register a flight");
bytes32 key = getFlightKey(msg.sender, flightName, flightTime);
Flight storage flight = flights[key];
flight.isRegistered = true;
flight.statusCode = STATUS_CODE_UNKNOWN;
flight.updatedTimestamp = flightTime;
flight.airline = msg.sender;
emit FlightRegistered(flightName, flightTime, msg.sender);
}
/**
* @dev Passenger buys an insurance for a flight
* sender is the passenger
*
* @param flightName codename of the flight to be insured
*/
function buyInsurance(address airline,
string memory flightName,
uint256 flightTime) external payable requireIsOperational {
bytes32 key = getFlightKey(airline, flightName, flightTime);
require(flights[key].isRegistered, "Flight not registered");
require(flights[key].statusCode == STATUS_CODE_UNKNOWN,
"Cannot buy insurance on a flight that has already departed");
dataContract.buy{value: msg.value}(msg.sender, key);
emit InsuranceBought(airline, flightName, flightTime, msg.sender, msg.value);
}
/**
* @dev Passenger (who is the sender of the call) claims the insurance payout
*/
function claimInsurance() external requireIsOperational {
dataContract.pay(payable(msg.sender));
emit InsuranceClaimPaid(msg.sender);
}
/**
* @dev Called after oracle has updated flight status
*
*/
function processFlightStatus(address airline,
string memory flight,
uint256 timestamp,
uint8 statusCode) internal requireIsOperational {
bytes32 key = getFlightKey(airline, flight, timestamp);
require(flights[key].isRegistered, "Flight not registered");
flights[key].statusCode = statusCode;
if (statusCode == STATUS_CODE_LATE_AIRLINE) {
// Check if passenger has insurance and pay out if so
dataContract.creditInsurees(key);
}
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus(address airline, string memory flight, uint256 timestamp) external requireIsOperational {
uint8 index = getRandomIndex(msg.sender, 0);
// Generate a unique key for storing the request
bytes32 key = getFlightKey(index, airline, flight, timestamp);
ResponseInfo storage newResponse = oracleResponses[key];
newResponse.requester = msg.sender;
newResponse.isOpen = true;
emit OracleRequest(index, airline, flight, timestamp);
}
/**
* @dev Funds the airline
*/
function fundAirline() external payable requireIsOperational {
dataContract.fund{value: msg.value}(msg.sender);
}
// 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 => // Mapping key is the status code reported
mapping(address => bool)) responses; // This lets us group responses and identify
mapping(uint8 => uint256) nbResponses; // the response that majority of the oracles
// I have changed that from array to mapping(address => bool) to guarantee that one oracle
// votes only one. This meant that I needed to add the nbResponses mapping because we cannot
// get the length of the responses[key] mapping unlike an array
}
// Track all oracle responses
// Key = hash(index, airline, 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, uint256 nbVotes);
// 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);
// Register an oracle with the contract
function registerOracle() external payable requireIsOperational {
// Require registration fee
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({isRegistered: true, indexes: indexes});
}
function getMyIndexes() view external returns(uint8[3] memory) {
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 memory flight,
uint256 timestamp,
uint8 statusCode) external requireIsOperational {
require((oracles[msg.sender].indexes[0] == index) ||
(oracles[msg.sender].indexes[1] == index) ||
(oracles[msg.sender].indexes[2] == index),
"Index does not match oracle request");
bytes32 key = getFlightKey(index, airline, flight, timestamp);
require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request");
require(!oracleResponses[key].responses[statusCode][msg.sender],
"Oracle voted already");
oracleResponses[key].responses[statusCode][msg.sender] = true;
uint256 n = oracleResponses[key].nbResponses[statusCode];
oracleResponses[key].nbResponses[statusCode] = n + 1;
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, timestamp, statusCode, oracleResponses[key].nbResponses[statusCode]);
if (oracleResponses[key].nbResponses[statusCode] >= MIN_RESPONSES) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
// Handle flight status as appropriate
processFlightStatus(airline, flight, timestamp, statusCode);
}
}
function getFlightKey(uint8 index,
address airline,
string memory flight,
uint256 timestamp) pure internal returns(bytes32) {
return keccak256(abi.encodePacked(index, airline, flight, timestamp));
}
function getFlightKey(address airline,
string memory flight,
uint256 timestamp) pure internal returns(bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes(address account) internal view returns(uint8[3] memory) {
uint8[3] memory indexes;
uint8 nonce = 0;
indexes[0] = getRandomIndex(account, nonce++);
indexes[1] = indexes[0];
while(indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account, nonce++);
if (nonce == 250) { // Break the cycle here and give up
break;
}
}
indexes[2] = indexes[1];
while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account, nonce++);
if (nonce > 250) {
break;
}
}
return indexes;
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex(address account, uint8 nonce) internal view returns (uint8) {
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
// This actually causes bugs because nonce can become bigger than block.number
//uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue);
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
}
| Returns array of three non-duplicating integers from 0-9 Pseudo random number...the incrementing nonce adds variation This actually causes bugs because nonce can become bigger than block.numberuint8 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} | function getRandomIndex(address account, uint8 nonce) internal view returns (uint8) {
uint8 maxValue = 10;
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce), account))) % maxValue);
return random;
}
| 15,869,979 | [
1,
1356,
526,
434,
8925,
1661,
17,
12262,
1776,
12321,
628,
374,
17,
29,
453,
9091,
2744,
1300,
2777,
5787,
5504,
310,
7448,
4831,
14761,
1220,
6013,
14119,
22398,
2724,
7448,
848,
12561,
18983,
2353,
1203,
18,
2696,
11890,
28,
2744,
273,
2254,
28,
12,
11890,
5034,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
2629,
2816,
12,
2629,
18,
2696,
300,
7448,
9904,
3631,
2236,
20349,
738,
18666,
1769,
430,
261,
12824,
405,
16927,
13,
288,
565,
7448,
273,
374,
31,
282,
4480,
1338,
2158,
1203,
17612,
364,
1142,
8303,
4398,
1427,
732,
5855,
97,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
20581,
1016,
12,
2867,
2236,
16,
2254,
28,
7448,
13,
2713,
1476,
1135,
261,
11890,
28,
13,
288,
203,
3639,
2254,
28,
18666,
273,
1728,
31,
203,
203,
3639,
2254,
28,
2744,
273,
2254,
28,
12,
11890,
5034,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
2629,
2816,
12,
2629,
18,
2696,
300,
7448,
3631,
2236,
20349,
738,
18666,
1769,
203,
203,
203,
3639,
327,
2744,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xDb80166478D50EDEFc4dD72c304d44D270c6b494/sources/contracts/core/libs/Structs.sol | user claims this value for its account in the group
| uint256 claimedValue; | 1,931,125 | [
1,
1355,
11955,
333,
460,
364,
2097,
2236,
316,
326,
1041,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
2254,
5034,
7516,
329,
620,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/56/0xa83B3E821F6CF63Cde35c9aC7012c00bF57a438D/sources/contracts/NewAlver.sol | Get the liquidity backing | function getLiquidityBacking(uint256 accuracy) public view returns (uint256) {
return accuracy.mul(balanceOf(pair).mul(2)).div(getCirculatingSupply());
}
| 3,245,888 | [
1,
967,
326,
4501,
372,
24237,
15394,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
9014,
18988,
24237,
2711,
310,
12,
11890,
5034,
15343,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
15343,
18,
16411,
12,
12296,
951,
12,
6017,
2934,
16411,
12,
22,
13,
2934,
2892,
12,
588,
10887,
1934,
1776,
3088,
1283,
10663,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.6.0;
contract Nest_NToken_OfferMain {
using SafeMath for uint256;
using address_make_payable for address;
using SafeERC20 for ERC20;
// Offering data structure
struct Nest_NToken_OfferPriceData {
// The unique identifier is determined by the position of the offer in the array, and is converted to each other through a fixed algorithm (toindex(), toaddress())
address owner; // Offering owner
bool deviate; // Whether it deviates
address tokenAddress; // The erc20 contract address of the target offer token
uint256 ethAmount; // The ETH amount in the offer list
uint256 tokenAmount; // The token amount in the offer list
uint256 dealEthAmount; // The remaining number of tradable ETH
uint256 dealTokenAmount; // The remaining number of tradable tokens
uint256 blockNum; // The block number where the offer is located
uint256 serviceCharge; // The fee for mining
// Determine whether the asset has been collected by judging that ethamount, tokenamount, and servicecharge are all 0
}
Nest_NToken_OfferPriceData [] _prices; // Array used to save offers
Nest_3_VoteFactory _voteFactory; // Voting contract
Nest_3_OfferPrice _offerPrice; // Price contract
Nest_NToken_TokenMapping _tokenMapping; // NToken mapping contract
ERC20 _nestToken; // nestToken
Nest_3_Abonus _abonus; // Bonus pool
uint256 _miningETH = 10; // Offering mining fee ratio
uint256 _tranEth = 1; // Taker fee ratio
uint256 _tranAddition = 2; // Additional transaction multiple
uint256 _leastEth = 10 ether; // Minimum offer of ETH
uint256 _offerSpan = 10 ether; // ETH Offering span
uint256 _deviate = 10; // Price deviation - 10%
uint256 _deviationFromScale = 10; // Deviation from asset scale
uint256 _ownerMining = 5; // Creator ratio
uint256 _afterMiningAmount = 0.4 ether; // Stable period mining amount
uint32 _blockLimit = 25; // Block interval upper limit
uint256 _blockAttenuation = 2400000; // Block decay interval
mapping(uint256 => mapping(address => uint256)) _blockOfferAmount; // Block offer times - block number=>token address=>offer fee
mapping(uint256 => mapping(address => uint256)) _blockMining; // Offering block mining amount - block number=>token address=>mining amount
uint256[10] _attenuationAmount; // Mining decay list
// Log token contract address
event OFFERTOKENCONTRACTADDRESS732(address contractAddress); //inject NONSTANDARD NAMING
// Log offering contract, token address, amount of ETH, amount of ERC20, delayed block, mining fee
event OFFERCONTRACTADDRESS317(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount, uint256 continued,uint256 mining); //inject NONSTANDARD NAMING
// Log transaction sender, transaction token, transaction amount, purchase token address, purchase token amount, transaction offering contract address, transaction user address
event OFFERTRAN368(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner); //inject NONSTANDARD NAMING
// Log current block, current block mined amount, token address
event OREDRAWINGLOG324(uint256 nowBlock, uint256 blockAmount, address tokenAddress); //inject NONSTANDARD NAMING
// Log offering block, token address, token offered times
event MININGLOG206(uint256 blockNum, address tokenAddress, uint256 offerTimes); //inject NONSTANDARD NAMING
constructor (address voteFactory) public {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.CHECKADDRESS430("nest.v3.offerPrice")));
_nestToken = ERC20(voteFactoryMap.CHECKADDRESS430("nest"));
_abonus = Nest_3_Abonus(voteFactoryMap.CHECKADDRESS430("nest.v3.abonus"));
_tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.CHECKADDRESS430("nest.nToken.tokenMapping")));
uint256 blockAmount = 4 ether;
for (uint256 i = 0; i < 10; i ++) {
_attenuationAmount[i] = blockAmount;
blockAmount = blockAmount.MUL982(8).DIV757(10);
}
}
function CHANGEMAPPING259(address voteFactory) public ONLYOWNER202 { //inject NONSTANDARD NAMING
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.CHECKADDRESS430("nest.v3.offerPrice")));
_nestToken = ERC20(voteFactoryMap.CHECKADDRESS430("nest"));
_abonus = Nest_3_Abonus(voteFactoryMap.CHECKADDRESS430("nest.v3.abonus"));
_tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.CHECKADDRESS430("nest.nToken.tokenMapping")));
}
function OFFER735(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable { //inject NONSTANDARD NAMING
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
address nTokenAddress = _tokenMapping.CHECKTOKENMAPPING799(erc20Address);
require(nTokenAddress != address(0x0));
// Judge whether the price deviates
uint256 ethMining;
bool isDeviate = COMPARATIVEPRICE616(ethAmount,erc20Amount,erc20Address);
if (isDeviate) {
require(ethAmount >= _leastEth.MUL982(_deviationFromScale), "EthAmount needs to be no less than 10 times of the minimum scale");
ethMining = _leastEth.MUL982(_miningETH).DIV757(1000);
} else {
ethMining = ethAmount.MUL982(_miningETH).DIV757(1000);
}
require(msg.value >= ethAmount.ADD379(ethMining), "msg.value needs to be equal to the quoted eth quantity plus Mining handling fee");
uint256 subValue = msg.value.SUB918(ethAmount.ADD379(ethMining));
if (subValue > 0) {
REPAYETH964(address(msg.sender), subValue);
}
// Create an offer
CREATEOFFER725(ethAmount, erc20Amount, erc20Address,isDeviate, ethMining);
// Transfer in offer asset - erc20 to this contract
ERC20(erc20Address).SAFETRANSFERFROM181(address(msg.sender), address(this), erc20Amount);
_abonus.SWITCHTOETHFORNTOKENOFFER869.value(ethMining)(nTokenAddress);
// Mining
if (_blockOfferAmount[block.number][erc20Address] == 0) {
uint256 miningAmount = OREDRAWING657(nTokenAddress);
Nest_NToken nToken = Nest_NToken(nTokenAddress);
nToken.TRANSFER16(nToken.CHECKBIDDER306(), miningAmount.MUL982(_ownerMining).DIV757(100));
_blockMining[block.number][erc20Address] = miningAmount.SUB918(miningAmount.MUL982(_ownerMining).DIV757(100));
}
_blockOfferAmount[block.number][erc20Address] = _blockOfferAmount[block.number][erc20Address].ADD379(ethMining);
}
function CREATEOFFER725(uint256 ethAmount, uint256 erc20Amount, address erc20Address, bool isDeviate, uint256 mining) private { //inject NONSTANDARD NAMING
// Check offer conditions
require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale");
require(ethAmount % _offerSpan == 0, "Non compliant asset span");
require(erc20Amount % (ethAmount.DIV757(_offerSpan)) == 0, "Asset quantity is not divided");
require(erc20Amount > 0);
// Create offering contract
emit OFFERCONTRACTADDRESS317(TOADDRESS719(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining);
_prices.push(Nest_NToken_OfferPriceData(
msg.sender,
isDeviate,
erc20Address,
ethAmount,
erc20Amount,
ethAmount,
erc20Amount,
block.number,
mining
));
// Record price
_offerPrice.ADDPRICE894(ethAmount, erc20Amount, block.number.ADD379(_blockLimit), erc20Address, address(msg.sender));
}
// Convert offer address into index in offer array
function TOINDEX783(address contractAddress) public pure returns(uint256) { //inject NONSTANDARD NAMING
return uint256(contractAddress);
}
// Convert index in offer array into offer address
function TOADDRESS719(uint256 index) public pure returns(address) { //inject NONSTANDARD NAMING
return address(index);
}
function TURNOUT418(address contractAddress) public { //inject NONSTANDARD NAMING
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 index = TOINDEX783(contractAddress);
Nest_NToken_OfferPriceData storage offerPriceData = _prices[index];
require(CHECKCONTRACTSTATE995(offerPriceData.blockNum) == 1, "Offer status error");
// Withdraw ETH
if (offerPriceData.ethAmount > 0) {
uint256 payEth = offerPriceData.ethAmount;
offerPriceData.ethAmount = 0;
REPAYETH964(offerPriceData.owner, payEth);
}
// Withdraw erc20
if (offerPriceData.tokenAmount > 0) {
uint256 payErc = offerPriceData.tokenAmount;
offerPriceData.tokenAmount = 0;
ERC20(address(offerPriceData.tokenAddress)).TRANSFER16(offerPriceData.owner, payErc);
}
// Mining settlement
if (offerPriceData.serviceCharge > 0) {
MINING254(offerPriceData.blockNum, offerPriceData.tokenAddress, offerPriceData.serviceCharge, offerPriceData.owner);
offerPriceData.serviceCharge = 0;
}
}
function SENDETHBUYERC123(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { //inject NONSTANDARD NAMING
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 serviceCharge = tranEthAmount.MUL982(_tranEth).DIV757(1000);
require(msg.value == ethAmount.ADD379(tranEthAmount).ADD379(serviceCharge), "msg.value needs to be equal to the quotation eth quantity plus transaction eth plus");
require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span");
// Get the offer data structure
uint256 index = TOINDEX783(contractAddress);
Nest_NToken_OfferPriceData memory offerPriceData = _prices[index];
// Check the price, compare the current offer to the last effective price
bool thisDeviate = COMPARATIVEPRICE616(ethAmount,tokenAmount,tranTokenAddress);
bool isDeviate;
if (offerPriceData.deviate == true) {
isDeviate = true;
} else {
isDeviate = thisDeviate;
}
// Limit the taker order only be twice the amount of the offer to prevent large-amount attacks
if (offerPriceData.deviate) {
// The taker order deviates x2
require(ethAmount >= tranEthAmount.MUL982(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
} else {
if (isDeviate) {
// If the taken offer is normal and the taker order deviates x10
require(ethAmount >= tranEthAmount.MUL982(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale");
} else {
// If the taken offer is normal and the taker order is normal x2
require(ethAmount >= tranEthAmount.MUL982(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
}
}
// Check whether the conditions for taker order are satisfied
require(CHECKCONTRACTSTATE995(offerPriceData.blockNum) == 0, "Offer status error");
require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth");
require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token");
require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address");
require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount");
// Update the offer information
offerPriceData.ethAmount = offerPriceData.ethAmount.ADD379(tranEthAmount);
offerPriceData.tokenAmount = offerPriceData.tokenAmount.SUB918(tranTokenAmount);
offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.SUB918(tranEthAmount);
offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.SUB918(tranTokenAmount);
_prices[index] = offerPriceData;
// Create a new offer
CREATEOFFER725(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0);
// Transfer in erc20 + offer asset to this contract
if (tokenAmount > tranTokenAmount) {
ERC20(tranTokenAddress).SAFETRANSFERFROM181(address(msg.sender), address(this), tokenAmount.SUB918(tranTokenAmount));
} else {
ERC20(tranTokenAddress).SAFETRANSFER797(address(msg.sender), tranTokenAmount.SUB918(tokenAmount));
}
// Modify price
_offerPrice.CHANGEPRICE820(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.ADD379(_blockLimit));
emit OFFERTRAN368(address(msg.sender), address(0x0), tranEthAmount, address(tranTokenAddress), tranTokenAmount, contractAddress, offerPriceData.owner);
// Transfer fee
if (serviceCharge > 0) {
address nTokenAddress = _tokenMapping.CHECKTOKENMAPPING799(tranTokenAddress);
_abonus.SWITCHTOETH95.value(serviceCharge)(nTokenAddress);
}
}
function SENDERCBUYETH398(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { //inject NONSTANDARD NAMING
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 serviceCharge = tranEthAmount.MUL982(_tranEth).DIV757(1000);
require(msg.value == ethAmount.SUB918(tranEthAmount).ADD379(serviceCharge), "msg.value needs to be equal to the quoted eth quantity plus transaction handling fee");
require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span");
// Get the offer data structure
uint256 index = TOINDEX783(contractAddress);
Nest_NToken_OfferPriceData memory offerPriceData = _prices[index];
// Check the price, compare the current offer to the last effective price
bool thisDeviate = COMPARATIVEPRICE616(ethAmount,tokenAmount,tranTokenAddress);
bool isDeviate;
if (offerPriceData.deviate == true) {
isDeviate = true;
} else {
isDeviate = thisDeviate;
}
// Limit the taker order only be twice the amount of the offer to prevent large-amount attacks
if (offerPriceData.deviate) {
// The taker order deviates x2
require(ethAmount >= tranEthAmount.MUL982(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
} else {
if (isDeviate) {
// If the taken offer is normal and the taker order deviates x10
require(ethAmount >= tranEthAmount.MUL982(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale");
} else {
// If the taken offer is normal and the taker order is normal x2
require(ethAmount >= tranEthAmount.MUL982(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
}
}
// Check whether the conditions for taker order are satisfied
require(CHECKCONTRACTSTATE995(offerPriceData.blockNum) == 0, "Offer status error");
require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth");
require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token");
require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address");
require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount");
// Update the offer information
offerPriceData.ethAmount = offerPriceData.ethAmount.SUB918(tranEthAmount);
offerPriceData.tokenAmount = offerPriceData.tokenAmount.ADD379(tranTokenAmount);
offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.SUB918(tranEthAmount);
offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.SUB918(tranTokenAmount);
_prices[index] = offerPriceData;
// Create a new offer
CREATEOFFER725(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0);
// Transfer in erc20 + offer asset to this contract
ERC20(tranTokenAddress).SAFETRANSFERFROM181(address(msg.sender), address(this), tranTokenAmount.ADD379(tokenAmount));
// Modify price
_offerPrice.CHANGEPRICE820(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.ADD379(_blockLimit));
emit OFFERTRAN368(address(msg.sender), address(tranTokenAddress), tranTokenAmount, address(0x0), tranEthAmount, contractAddress, offerPriceData.owner);
// Transfer fee
if (serviceCharge > 0) {
address nTokenAddress = _tokenMapping.CHECKTOKENMAPPING799(tranTokenAddress);
_abonus.SWITCHTOETH95.value(serviceCharge)(nTokenAddress);
}
}
function OREDRAWING657(address ntoken) private returns(uint256) { //inject NONSTANDARD NAMING
Nest_NToken miningToken = Nest_NToken(ntoken);
(uint256 createBlock, uint256 recentlyUsedBlock) = miningToken.CHECKBLOCKINFO350();
uint256 attenuationPointNow = block.number.SUB918(createBlock).DIV757(_blockAttenuation);
uint256 miningAmount = 0;
uint256 attenuation;
if (attenuationPointNow > 9) {
attenuation = _afterMiningAmount;
} else {
attenuation = _attenuationAmount[attenuationPointNow];
}
miningAmount = attenuation.MUL982(block.number.SUB918(recentlyUsedBlock));
miningToken.INCREASETOTAL78(miningAmount);
emit OREDRAWINGLOG324(block.number, miningAmount, ntoken);
return miningAmount;
}
function MINING254(uint256 blockNum, address token, uint256 serviceCharge, address owner) private returns(uint256) { //inject NONSTANDARD NAMING
// Block mining amount*offer fee/block offer fee
uint256 miningAmount = _blockMining[blockNum][token].MUL982(serviceCharge).DIV757(_blockOfferAmount[blockNum][token]);
// Transfer NToken
Nest_NToken nToken = Nest_NToken(address(_tokenMapping.CHECKTOKENMAPPING799(token)));
require(nToken.TRANSFER16(address(owner), miningAmount), "Transfer failure");
emit MININGLOG206(blockNum, token,_blockOfferAmount[blockNum][token]);
return miningAmount;
}
// Compare order prices
function COMPARATIVEPRICE616(uint256 myEthValue, uint256 myTokenValue, address token) private view returns(bool) { //inject NONSTANDARD NAMING
(uint256 frontEthValue, uint256 frontTokenValue) = _offerPrice.UPDATEANDCHECKPRICEPRIVATE349(token);
if (frontEthValue == 0 || frontTokenValue == 0) {
return false;
}
uint256 maxTokenAmount = myEthValue.MUL982(frontTokenValue).MUL982(uint256(100).ADD379(_deviate)).DIV757(frontEthValue.MUL982(100));
if (myTokenValue <= maxTokenAmount) {
uint256 minTokenAmount = myEthValue.MUL982(frontTokenValue).MUL982(uint256(100).SUB918(_deviate)).DIV757(frontEthValue.MUL982(100));
if (myTokenValue >= minTokenAmount) {
return false;
}
}
return true;
}
// Check contract status
function CHECKCONTRACTSTATE995(uint256 createBlock) public view returns (uint256) { //inject NONSTANDARD NAMING
if (block.number.SUB918(createBlock) > _blockLimit) {
return 1;
}
return 0;
}
// Transfer ETH
function REPAYETH964(address accountAddress, uint256 asset) private { //inject NONSTANDARD NAMING
address payable addr = accountAddress.MAKE_PAYABLE861();
addr.transfer(asset);
}
// View the upper limit of the block interval
function CHECKBLOCKLIMIT652() public view returns(uint256) { //inject NONSTANDARD NAMING
return _blockLimit;
}
// View taker fee ratio
function CHECKTRANETH271() public view returns (uint256) { //inject NONSTANDARD NAMING
return _tranEth;
}
// View additional transaction multiple
function CHECKTRANADDITION123() public view returns(uint256) { //inject NONSTANDARD NAMING
return _tranAddition;
}
// View minimum offering ETH
function CHECKLEASTETH415() public view returns(uint256) { //inject NONSTANDARD NAMING
return _leastEth;
}
// View offering ETH span
function CHECKOFFERSPAN954() public view returns(uint256) { //inject NONSTANDARD NAMING
return _offerSpan;
}
// View block offering amount
function CHECKBLOCKOFFERAMOUNT357(uint256 blockNum, address token) public view returns (uint256) { //inject NONSTANDARD NAMING
return _blockOfferAmount[blockNum][token];
}
// View offering block mining amount
function CHECKBLOCKMINING594(uint256 blockNum, address token) public view returns (uint256) { //inject NONSTANDARD NAMING
return _blockMining[blockNum][token];
}
// View offering mining amount
function CHECKOFFERMINING245(uint256 blockNum, address token, uint256 serviceCharge) public view returns (uint256) { //inject NONSTANDARD NAMING
if (serviceCharge == 0) {
return 0;
} else {
return _blockMining[blockNum][token].MUL982(serviceCharge).DIV757(_blockOfferAmount[blockNum][token]);
}
}
// View the owner allocation ratio
function CHECKOWNERMINING462() public view returns(uint256) { //inject NONSTANDARD NAMING
return _ownerMining;
}
// View the mining decay
function CHECKATTENUATIONAMOUNT848(uint256 num) public view returns(uint256) { //inject NONSTANDARD NAMING
return _attenuationAmount[num];
}
// Modify taker order fee ratio
function CHANGETRANETH866(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING
_tranEth = num;
}
// Modify block interval upper limit
function CHANGEBLOCKLIMIT22(uint32 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING
_blockLimit = num;
}
// Modify additional transaction multiple
function CHANGETRANADDITION884(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING
require(num > 0, "Parameter needs to be greater than 0");
_tranAddition = num;
}
// Modify minimum offering ETH
function CHANGELEASTETH405(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING
require(num > 0, "Parameter needs to be greater than 0");
_leastEth = num;
}
// Modify offering ETH span
function CHANGEOFFERSPAN492(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING
require(num > 0, "Parameter needs to be greater than 0");
_offerSpan = num;
}
// Modify price deviation
function CHANGEKDEVIATE724(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING
_deviate = num;
}
// Modify the deviation from scale
function CHANGEDEVIATIONFROMSCALE300(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING
_deviationFromScale = num;
}
// Modify the owner allocation ratio
function CHANGEOWNERMINING351(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING
_ownerMining = num;
}
// Modify the mining decay
function CHANGEATTENUATIONAMOUNT1(uint256 firstAmount, uint256 top, uint256 bottom) public ONLYOWNER202 { //inject NONSTANDARD NAMING
uint256 blockAmount = firstAmount;
for (uint256 i = 0; i < 10; i ++) {
_attenuationAmount[i] = blockAmount;
blockAmount = blockAmount.MUL982(top).DIV757(bottom);
}
}
// Vote administrators only
modifier ONLYOWNER202(){ //inject NONSTANDARD NAMING
require(_voteFactory.CHECKOWNERS558(msg.sender), "No authority");
_;
}
function GETPRICECOUNT52() view public returns (uint256) { //inject NONSTANDARD NAMING
return _prices.length;
}
function GETPRICE258(uint256 priceIndex) view public returns (string memory) { //inject NONSTANDARD NAMING
// The buffer array used to generate the result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
index = WRITEOFFERPRICEDATA490(priceIndex, _prices[priceIndex], buf, index);
// Generate the result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
function FIND608(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) { //inject NONSTANDARD NAMING
// Buffer array used to generate result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
// Calculate search interval i and end
uint256 i = _prices.length;
uint256 end = 0;
if (start != address(0)) {
i = TOINDEX783(start);
}
if (i > maxFindCount) {
end = i - maxFindCount;
}
// Loop search, write qualified records into buffer
while (count > 0 && i-- > end) {
Nest_NToken_OfferPriceData memory price = _prices[i];
if (price.owner == owner) {
--count;
index = WRITEOFFERPRICEDATA490(i, price, buf, index);
}
}
// Generate result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
function LIST901(uint256 offset, uint256 count, uint256 order) view public returns (string memory) { //inject NONSTANDARD NAMING
// Buffer array used to generate result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
// Find search interval i and end
uint256 i = 0;
uint256 end = 0;
if (order == 0) {
// Reverse order, in default
// Calculate search interval i and end
if (offset < _prices.length) {
i = _prices.length - offset;
}
if (count < i) {
end = i - count;
}
// Write records in the target interval into the buffer
while (i-- > end) {
index = WRITEOFFERPRICEDATA490(i, _prices[i], buf, index);
}
} else {
// Ascending order
// Calculate the search interval i and end
if (offset < _prices.length) {
i = offset;
} else {
i = _prices.length;
}
end = i + count;
if(end > _prices.length) {
end = _prices.length;
}
// Write the records in the target interval into the buffer
while (i < end) {
index = WRITEOFFERPRICEDATA490(i, _prices[i], buf, index);
++i;
}
}
// Generate the result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
// Write the offer data into the buffer and return the buffer index
function WRITEOFFERPRICEDATA490(uint256 priceIndex, Nest_NToken_OfferPriceData memory price, bytes memory buf, uint256 index) pure private returns (uint256) { //inject NONSTANDARD NAMING
index = WRITEADDRESS338(TOADDRESS719(priceIndex), buf, index);
buf[index++] = byte(uint8(44));
index = WRITEADDRESS338(price.owner, buf, index);
buf[index++] = byte(uint8(44));
index = WRITEADDRESS338(price.tokenAddress, buf, index);
buf[index++] = byte(uint8(44));
index = WRITEUINT859(price.ethAmount, buf, index);
buf[index++] = byte(uint8(44));
index = WRITEUINT859(price.tokenAmount, buf, index);
buf[index++] = byte(uint8(44));
index = WRITEUINT859(price.dealEthAmount, buf, index);
buf[index++] = byte(uint8(44));
index = WRITEUINT859(price.dealTokenAmount, buf, index);
buf[index++] = byte(uint8(44));
index = WRITEUINT859(price.blockNum, buf, index);
buf[index++] = byte(uint8(44));
index = WRITEUINT859(price.serviceCharge, buf, index);
buf[index++] = byte(uint8(44));
return index;
}
// Convert integer to string in decimal form, write the string into the buffer, and return the buffer index
function WRITEUINT859(uint256 iv, bytes memory buf, uint256 index) pure public returns (uint256) { //inject NONSTANDARD NAMING
uint256 i = index;
do {
buf[index++] = byte(uint8(iv % 10 +48));
iv /= 10;
} while (iv > 0);
for (uint256 j = index; j > i; ++i) {
byte t = buf[i];
buf[i] = buf[--j];
buf[j] = t;
}
return index;
}
// Convert the address to a hexadecimal string and write it into the buffer, and return the buffer index
function WRITEADDRESS338(address addr, bytes memory buf, uint256 index) pure private returns (uint256) { //inject NONSTANDARD NAMING
uint256 iv = uint256(addr);
uint256 i = index + 40;
do {
uint256 w = iv % 16;
if(w < 10) {
buf[index++] = byte(uint8(w +48));
} else {
buf[index++] = byte(uint8(w +87));
}
iv /= 16;
} while (index < i);
i -= 40;
for (uint256 j = index; j > i; ++i) {
byte t = buf[i];
buf[i] = buf[--j];
buf[j] = t;
}
return index;
}
}
// Price contract
interface Nest_3_OfferPrice {
// Add price data
function ADDPRICE894(uint256 ethAmount, uint256 tokenAmount, uint256 endBlock, address tokenAddress, address offerOwner) external; //inject NONSTANDARD NAMING
// Modify price
function CHANGEPRICE820(uint256 ethAmount, uint256 tokenAmount, address tokenAddress, uint256 endBlock) external; //inject NONSTANDARD NAMING
function UPDATEANDCHECKPRICEPRIVATE349(address tokenAddress) external view returns(uint256 ethAmount, uint256 erc20Amount); //inject NONSTANDARD NAMING
}
// Voting contract
interface Nest_3_VoteFactory {
// Check address
function CHECKADDRESS430(string calldata name) external view returns (address contractAddress); //inject NONSTANDARD NAMING
// Check whether an administrator
function CHECKOWNERS558(address man) external view returns (bool); //inject NONSTANDARD NAMING
}
// NToken contract
interface Nest_NToken {
// Additional issuance
function INCREASETOTAL78(uint256 value) external; //inject NONSTANDARD NAMING
// Check mining information
function CHECKBLOCKINFO350() external view returns(uint256 createBlock, uint256 recentlyUsedBlock); //inject NONSTANDARD NAMING
// Check creator
function CHECKBIDDER306() external view returns(address); //inject NONSTANDARD NAMING
function TOTALSUPPLY249() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF133(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER16(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE798(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE147(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM462(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL26(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// NToken mapping contract
interface Nest_NToken_TokenMapping {
// Check token mapping
function CHECKTOKENMAPPING799(address token) external view returns (address); //inject NONSTANDARD NAMING
}
// Bonus pool contract
interface Nest_3_Abonus {
function SWITCHTOETH95(address token) external payable; //inject NONSTANDARD NAMING
function SWITCHTOETHFORNTOKENOFFER869(address token) external payable; //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD379(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB918(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB918(a, b, "SafeMath: subtraction overflow");
}
function SUB918(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 MUL982(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV757(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV757(a, b, "SafeMath: division by zero");
}
function DIV757(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function MOD863(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD863(a, b, "SafeMath: modulo by zero");
}
function MOD863(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library address_make_payable {
function MAKE_PAYABLE861(address x) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(x));
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER797(ERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN10(token, abi.encodeWithSelector(token.TRANSFER16.selector, to, value));
}
function SAFETRANSFERFROM181(ERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN10(token, abi.encodeWithSelector(token.TRANSFERFROM462.selector, from, to, value));
}
function SAFEAPPROVE632(ERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE798(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN10(token, abi.encodeWithSelector(token.APPROVE147.selector, spender, value));
}
function SAFEINCREASEALLOWANCE243(ERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE798(address(this), spender).ADD379(value);
CALLOPTIONALRETURN10(token, abi.encodeWithSelector(token.APPROVE147.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE715(ERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE798(address(this), spender).SUB918(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN10(token, abi.encodeWithSelector(token.APPROVE147.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN10(ERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT477(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface ERC20 {
function TOTALSUPPLY249() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF133(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER16(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE798(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE147(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM462(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL26(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library Address {
function ISCONTRACT477(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function SENDVALUE528(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
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");
}
} | inject NONSTANDARD NAMING
| function CHANGETRANETH866(uint256 num) public ONLYOWNER202 { | 14,093,895 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6469,
1258,
3264,
54,
1258,
1584,
44,
5292,
26,
12,
11890,
5034,
818,
13,
1071,
20747,
29602,
18212,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/5/0xA109b34B1974C1f6BA554607F46E202926728E14/sources/src/CDPVault.sol | calc. ratio between liquid credit and total credit claim for all fixable epochs | uint256 claimRatio;
| 16,850,852 | [
1,
12448,
18,
7169,
3086,
4501,
26595,
12896,
471,
2078,
12896,
7516,
364,
777,
2917,
429,
25480,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
7516,
8541,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43113/0x5F54c25cB1172EE83715c4CbB0a2bF1CE02Bd1Fc/sources/money.sol | 私有合约 定义一个所有者地址 私有变量 生命所有权转移事件 构造 | abstract contract Ownable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
pragma solidity ^0.8.0;
constructor() {
_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;
}
}
| 13,186,067 | [
1,
168,
105,
228,
167,
255,
236,
166,
243,
235,
168,
123,
104,
225,
166,
111,
253,
165,
122,
236,
165,
121,
227,
165,
121,
108,
167,
236,
227,
167,
255,
236,
169,
227,
232,
166,
255,
113,
166,
256,
227,
225,
168,
105,
228,
167,
255,
236,
166,
242,
251,
170,
234,
242,
225,
168,
247,
258,
166,
244,
126,
167,
236,
227,
167,
255,
236,
167,
256,
230,
169,
126,
110,
168,
105,
124,
165,
123,
238,
165,
124,
119,
225,
167,
257,
231,
170,
227,
259,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
14223,
6914,
288,
203,
565,
1758,
3238,
389,
8443,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
203,
3639,
1758,
8808,
2416,
5541,
16,
203,
3639,
1758,
8808,
394,
5541,
203,
565,
11272,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
3885,
1435,
288,
203,
3639,
389,
8443,
273,
1234,
18,
15330,
31,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
12,
2867,
12,
20,
3631,
389,
8443,
1769,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
291,
5541,
10663,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
353,
5541,
1435,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1234,
18,
15330,
422,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
445,
1654,
8386,
5460,
12565,
1435,
1071,
1338,
5541,
288,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
1758,
12,
20,
10019,
203,
3639,
389,
8443,
273,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
13866,
5460,
12565,
12,
2704,
5541,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
13866,
5460,
12565,
12,
2867,
394,
5541,
13,
2713,
288,
203,
3639,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
10019,
203,
3639,
3626,
14223,
2
] |
pragma solidity ^0.4.24;
/** ----------------------MonetaryCoin V1.0.0 ------------------------*/
/**
* Homepage: https://MonetaryCoin.org Distribution: https://MonetaryCoin.io
*
* Full source code: https://github.com/Monetary-Foundation/MonetaryCoin
*
* Licenced MIT - The Monetary Foundation 2018
*
*/
/**
* @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 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 transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title 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;
}
}
/**
* @title MineableToken
* @dev ERC20 Token with Pos mining.
* The blockReward_ is controlled by a GDP oracle tied to the national identity or currency union identity of the subject MonetaryCoin.
* This type of mining will be used during both the initial distribution period and when GDP growth is positive.
* For mining during negative growth period please refer to MineableM5Token.sol.
* Unlike standard erc20 token, the totalSupply is sum(all user balances) + totalStake instead of sum(all user balances).
*/
contract MineableToken is MintableToken {
event Commit(address indexed from, uint value,uint atStake, int onBlockReward);
event Withdraw(address indexed from, uint reward, uint commitment);
uint256 totalStake_ = 0;
int256 blockReward_; //could be positive or negative according to GDP
struct Commitment {
uint256 value; // value commited to mining
uint256 onBlockNumber; // commitment done on block
uint256 atStake; // stake during commitment
int256 onBlockReward;
}
mapping( address => Commitment ) miners;
/**
* @dev commit _value for minning
* @notice the _value will be substructed from user balance and added to the stake.
* if user previously commited, add to an existing commitment.
* this is done by calling withdraw() then commit back previous commit + reward + new commit
* @param _value The amount to be commited.
* @return the commit value: _value OR prevCommit + reward + _value
*/
function commit(uint256 _value) public returns (uint256 commitmentValue) {
require(0 < _value);
require(_value <= balances[msg.sender]);
commitmentValue = _value;
uint256 prevCommit = miners[msg.sender].value;
//In case user already commited, withdraw and recommit
// new commitment value: prevCommit + reward + _value
if (0 < prevCommit) {
// withdraw Will revert if reward is negative
uint256 prevReward;
(prevReward, prevCommit) = withdraw();
commitmentValue = prevReward.add(prevCommit).add(_value);
}
// sub will revert if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(commitmentValue);
emit Transfer(msg.sender, address(0), commitmentValue);
totalStake_ = totalStake_.add(commitmentValue);
miners[msg.sender] = Commitment(
commitmentValue, // Commitment.value
block.number, // onBlockNumber
totalStake_, // atStake = current stake + commitments value
blockReward_ // onBlockReward
);
emit Commit(msg.sender, commitmentValue, totalStake_, blockReward_); // solium-disable-line
return commitmentValue;
}
/**
* @dev withdraw reward
* @return {
"uint256 reward": the new supply
"uint256 commitmentValue": the commitment to be returned
}
*/
function withdraw() public returns (uint256 reward, uint256 commitmentValue) {
require(miners[msg.sender].value > 0);
//will revert if reward is negative:
reward = getReward(msg.sender);
Commitment storage commitment = miners[msg.sender];
commitmentValue = commitment.value;
uint256 withdrawnSum = commitmentValue.add(reward);
totalStake_ = totalStake_.sub(commitmentValue);
totalSupply_ = totalSupply_.add(reward);
balances[msg.sender] = balances[msg.sender].add(withdrawnSum);
emit Transfer(address(0), msg.sender, commitmentValue.add(reward));
delete miners[msg.sender];
emit Withdraw(msg.sender, reward, commitmentValue); // solium-disable-line
return (reward, commitmentValue);
}
/**
* @dev Calculate the reward if withdraw() happans on this block
* @notice The reward is calculated by the formula:
* (numberOfBlocks) * (effectiveBlockReward) * (commitment.value) / (effectiveStake)
* effectiveBlockReward is the average between the block reward during commit and the block reward during the call
* effectiveStake is the average between the stake during the commit and the stake during call (liniar aproximation)
* @return An uint256 representing the reward amount
*/
function getReward(address _miner) public view returns (uint256) {
if (miners[_miner].value == 0) {
return 0;
}
Commitment storage commitment = miners[_miner];
int256 averageBlockReward = signedAverage(commitment.onBlockReward, blockReward_);
require(0 <= averageBlockReward);
uint256 effectiveBlockReward = uint256(averageBlockReward);
uint256 effectiveStake = average(commitment.atStake, totalStake_);
uint256 numberOfBlocks = block.number.sub(commitment.onBlockNumber);
uint256 miningReward = numberOfBlocks.mul(effectiveBlockReward).mul(commitment.value).div(effectiveStake);
return miningReward;
}
/**
* @dev Calculate the average of two integer numbers
* @notice 1.5 will be rounded toward zero
* @return An uint256 representing integer average
*/
function average(uint256 a, uint256 b) public pure returns (uint256) {
return a.add(b).div(2);
}
/**
* @dev Calculate the average of two signed integers numbers
* @notice 1.5 will be toward zero
* @return An int256 representing integer average
*/
function signedAverage(int256 a, int256 b) public pure returns (int256) {
int256 ans = a + b;
if (a > 0 && b > 0 && ans <= 0) {
require(false);
}
if (a < 0 && b < 0 && ans >= 0) {
require(false);
}
return ans / 2;
}
/**
* @dev Gets the commitment of the specified address.
* @param _miner The address to query the the commitment Of
* @return the amount commited.
*/
function commitmentOf(address _miner) public view returns (uint256) {
return miners[_miner].value;
}
/**
* @dev Gets the all fields for the commitment of the specified address.
* @param _miner The address to query the the commitment Of
* @return {
"uint256 value": the amount commited.
"uint256 onBlockNumber": block number of commitment.
"uint256 atStake": stake when commited.
"int256 onBlockReward": block reward when commited.
}
*/
function getCommitment(address _miner) public view
returns (
uint256 value, // value commited to mining
uint256 onBlockNumber, // commited on block
uint256 atStake, // stake during commit
int256 onBlockReward // block reward during commit
)
{
value = miners[_miner].value;
onBlockNumber = miners[_miner].onBlockNumber;
atStake = miners[_miner].atStake;
onBlockReward = miners[_miner].onBlockReward;
}
/**
* @dev the total stake
* @return the total stake
*/
function totalStake() public view returns (uint256) {
return totalStake_;
}
/**
* @dev the block reward
* @return the current block reward
*/
function blockReward() public view returns (int256) {
return blockReward_;
}
}
/**
* @title GDPOraclizedToken
* @dev This is an interface for the GDP Oracle to control the mining rate.
* For security reasons, two distinct functions were created:
* setPositiveGrowth() and setNegativeGrowth()
*/
contract GDPOraclizedToken is MineableToken {
event GDPOracleTransferred(address indexed previousOracle, address indexed newOracle);
event BlockRewardChanged(int oldBlockReward, int newBlockReward);
address GDPOracle_;
address pendingGDPOracle_;
/**
* @dev Modifier Throws if called by any account other than the GDPOracle.
*/
modifier onlyGDPOracle() {
require(msg.sender == GDPOracle_);
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingGDPOracle.
*/
modifier onlyPendingGDPOracle() {
require(msg.sender == pendingGDPOracle_);
_;
}
/**
* @dev Allows the current GDPOracle to transfer control to a newOracle.
* The new GDPOracle need to call claimOracle() to finalize
* @param newOracle The address to transfer ownership to.
*/
function transferGDPOracle(address newOracle) public onlyGDPOracle {
pendingGDPOracle_ = newOracle;
}
/**
* @dev Allows the pendingGDPOracle_ address to finalize the transfer.
*/
function claimOracle() onlyPendingGDPOracle public {
emit GDPOracleTransferred(GDPOracle_, pendingGDPOracle_);
GDPOracle_ = pendingGDPOracle_;
pendingGDPOracle_ = address(0);
}
/**
* @dev Chnage block reward according to GDP
* @param newBlockReward the new block reward in case of possible growth
*/
function setPositiveGrowth(int256 newBlockReward) public onlyGDPOracle returns(bool) {
// protect against error / overflow
require(0 <= newBlockReward);
emit BlockRewardChanged(blockReward_, newBlockReward);
blockReward_ = newBlockReward;
}
/**
* @dev Chnage block reward according to GDP
* @param newBlockReward the new block reward in case of negative growth
*/
function setNegativeGrowth(int256 newBlockReward) public onlyGDPOracle returns(bool) {
require(newBlockReward < 0);
emit BlockRewardChanged(blockReward_, newBlockReward);
blockReward_ = newBlockReward;
}
/**
* @dev get GDPOracle
* @return the address of the GDPOracle
*/
function GDPOracle() public view returns (address) { // solium-disable-line mixedcase
return GDPOracle_;
}
/**
* @dev get GDPOracle
* @return the address of the GDPOracle
*/
function pendingGDPOracle() public view returns (address) { // solium-disable-line mixedcase
return pendingGDPOracle_;
}
}
/**
* @title MineableM5Token
* @notice This contract adds the ability to mine for M5 tokens when growth is negative.
* The M5 token is a distinct ERC20 token that may be obtained only following a period of negative GDP growth.
* The logic for M5 mining will be finalized in advance of the close of the initial distribution period – see the White Paper for additional details.
* After upgrading this contract with the final M5 logic, finishUpgrade() will be called to permanently seal the upgradeability of the contract.
*/
contract MineableM5Token is GDPOraclizedToken {
event M5TokenUpgrade(address indexed oldM5Token, address indexed newM5Token);
event M5LogicUpgrade(address indexed oldM5Logic, address indexed newM5Logic);
event FinishUpgrade();
// The M5 token contract
address M5Token_;
// The contract to manage M5 mining logic.
address M5Logic_;
// The address which controls the upgrade process
address upgradeManager_;
// When isUpgradeFinished_ is true, no more upgrades is allowed
bool isUpgradeFinished_ = false;
/**
* @dev get the M5 token address
* @return M5 token address
*/
function M5Token() public view returns (address) {
return M5Token_;
}
/**
* @dev get the M5 logic contract address
* @return M5 logic contract address
*/
function M5Logic() public view returns (address) {
return M5Logic_;
}
/**
* @dev get the upgrade manager address
* @return the upgrade manager address
*/
function upgradeManager() public view returns (address) {
return upgradeManager_;
}
/**
* @dev get the upgrade status
* @return the upgrade status. if true, no more upgrades are possible.
*/
function isUpgradeFinished() public view returns (bool) {
return isUpgradeFinished_;
}
/**
* @dev Throws if called by any account other than the GDPOracle.
*/
modifier onlyUpgradeManager() {
require(msg.sender == upgradeManager_);
require(!isUpgradeFinished_);
_;
}
/**
* @dev Allows to set the M5 token contract
* @param newM5Token The address of the new contract
*/
function upgradeM5Token(address newM5Token) public onlyUpgradeManager { // solium-disable-line
require(newM5Token != address(0));
emit M5TokenUpgrade(M5Token_, newM5Token);
M5Token_ = newM5Token;
}
/**
* @dev Allows the upgrade the M5 logic contract
* @param newM5Logic The address of the new contract
*/
function upgradeM5Logic(address newM5Logic) public onlyUpgradeManager { // solium-disable-line
require(newM5Logic != address(0));
emit M5LogicUpgrade(M5Logic_, newM5Logic);
M5Logic_ = newM5Logic;
}
/**
* @dev Allows the upgrade the M5 logic contract and token at the same transaction
* @param newM5Token The address of a new M5 token
* @param newM5Logic The address of the new contract
*/
function upgradeM5(address newM5Token, address newM5Logic) public onlyUpgradeManager { // solium-disable-line
require(newM5Token != address(0));
require(newM5Logic != address(0));
emit M5TokenUpgrade(M5Token_, newM5Token);
emit M5LogicUpgrade(M5Logic_, newM5Logic);
M5Token_ = newM5Token;
M5Logic_ = newM5Logic;
}
/**
* @dev Function to dismiss the upgrade capability
* @return True if the operation was successful.
*/
function finishUpgrade() onlyUpgradeManager public returns (bool) {
isUpgradeFinished_ = true;
emit FinishUpgrade();
return true;
}
/**
* @dev Calculate the reward if withdrawM5() happans on this block
* @notice This is a wrapper, which calls and return result from M5Logic
* the actual logic is found in the M5Logic contract
* @param _miner The address of the _miner
* @return An uint256 representing the reward amount
*/
function getM5Reward(address _miner) public view returns (uint256) {
require(M5Logic_ != address(0));
if (miners[_miner].value == 0) {
return 0;
}
// check that effective block reward is indeed negative
require(signedAverage(miners[_miner].onBlockReward, blockReward_) < 0);
// return length (bytes)
uint32 returnSize = 32;
// target contract
address target = M5Logic_;
// method signeture for target contract
bytes32 signature = keccak256("getM5Reward(address)");
// size of calldata for getM5Reward function: 4 for signeture and 32 for one variable (address)
uint32 inputSize = 4 + 32;
// variable to check delegatecall result (success or failure)
uint8 callResult;
// result from target.getM5Reward()
uint256 result;
assembly { // solium-disable-line
// return _dest.delegatecall(msg.data)
mstore(0x0, signature) // 4 bytes of method signature
mstore(0x4, _miner) // 20 bytes of address
// delegatecall(g, a, in, insize, out, outsize) - call contract at address a with input mem[in..(in+insize))
// providing g gas and v wei and output area mem[out..(out+outsize)) returning 0 on error (eg. out of gas) and 1 on success
// keep caller and callvalue
callResult := delegatecall(sub(gas, 10000), target, 0x0, inputSize, 0x0, returnSize)
switch callResult
case 0
{ revert(0,0) }
default
{ result := mload(0x0) }
}
return result;
}
event WithdrawM5(address indexed from,uint commitment, uint M5Reward);
/**
* @dev withdraw M5 reward, only appied to mining when GDP is negative
* @return {
"uint256 reward": the new M5 supply
"uint256 commitmentValue": the commitment to be returned
}
*/
function withdrawM5() public returns (uint256 reward, uint256 commitmentValue) {
require(M5Logic_ != address(0));
require(M5Token_ != address(0));
require(miners[msg.sender].value > 0);
// will revert if reward is positive
reward = getM5Reward(msg.sender);
commitmentValue = miners[msg.sender].value;
require(M5Logic_.delegatecall(bytes4(keccak256("withdrawM5()")))); // solium-disable-line
return (reward,commitmentValue);
}
//triggered when user swaps m5Value of M5 tokens for value of regular tokens.
event Swap(address indexed from, uint256 M5Value, uint256 value);
/**
* @dev swap M5 tokens back to regular tokens when GDP is back to positive
* @param _value The amount of M5 tokens to swap for regular tokens
* @return true
*/
function swap(uint256 _value) public returns (bool) {
require(M5Logic_ != address(0));
require(M5Token_ != address(0));
require(M5Logic_.delegatecall(bytes4(keccak256("swap(uint256)")),_value)); // solium-disable-line
return true;
}
}
/**
* @title MCoin
* @dev The MonetaryCoin contract
* The MonetaryCoin contract allows for the creation of a new monetary coin.
* The supply of a minable coin in a period is defined by an oracle that reports GDP data from the country related to that coin.
* Example: If the GDP of a given country grows by 3%, then 3% more coins will be available for forging (i.e. mining) in the next period.
* Coins will be distributed by the proof of stake forging mechanism both during and after the initial distribution period.
* The Proof of stake forging is defined by the MineableToken.sol contract.
*/
contract MCoin is MineableM5Token {
string public name; // solium-disable-line uppercase
string public symbol; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
constructor(
string tokenName,
string tokenSymbol,
uint256 blockReward, // will be transformed using toDecimals()
address GDPOracle,
address upgradeManager
) public
{
require(GDPOracle != address(0));
require(upgradeManager != address(0));
name = tokenName;
symbol = tokenSymbol;
blockReward_ = toDecimals(blockReward);
emit BlockRewardChanged(0, blockReward_);
GDPOracle_ = GDPOracle;
emit GDPOracleTransferred(0x0, GDPOracle_);
M5Token_ = address(0);
M5Logic_ = address(0);
upgradeManager_ = upgradeManager;
}
function toDecimals(uint256 _value) pure internal returns (int256 value) {
value = int256 (
_value.mul(10 ** uint256(decimals))
);
assert(0 < value);
return value;
}
} | * @dev get GDPOracle @return the address of the GDPOracle/ | return pendingGDPOracle_;
| 911,008 | [
1,
588,
30176,
2419,
16873,
327,
326,
1758,
434,
326,
30176,
2419,
16873,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
327,
4634,
27338,
2419,
16873,
67,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.11;
/*
* The MIT License (MIT)
*
* 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
*/
// A base contract that implements the following concepts:
// 1. A smart contract with an owner
// 2. Methods that can only be called by the owner
// 3. Transferability of ownership
contract Owned {
// The address of the owner
address public owner;
// Constructor
function Owned() {
owner = msg.sender;
}
// A modifier that provides a pre-check as to whether the sender is the owner
modifier _onlyOwner {
if (msg.sender != owner) revert();
_;
}
// Transfers ownership to newOwner, given that the sender is the owner
function transferOwnership(address newOwner) _onlyOwner {
owner = newOwner;
}
}
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
contract Token is Owned {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
// Implementation of Token contract
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
/*
This Token Contract implements the standard token functionality (https://github.com/ethereum/EIPs/issues/20) as well as the following OPTIONAL extras intended for use by humans.
In other words. This is intended for deployment in something like a Token Factory or Mist wallet, and then used by humans.
Imagine coins, currencies, shares, voting weight, etc.
Machine-based, rapid creation of many tokens would not necessarily need these extra features or will be minted in other manners.
1) Initial Finite Supply (upon creation one specifies how much is minted).
2) In the absence of a token registry: Optional Decimal, Symbol & Name.
3) Optional approveAndCall() functionality to notify a contract if an approval() has occurred.
.*/
contract HumanStandardToken is StandardToken {
function() {
//if ether is sent to this address, send it back.
revert();
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme.
function HumanStandardToken(uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol) {
balances[msg.sender] = _initialAmount;
// Give the creator all initial tokens
totalSupply = _initialAmount;
// Update total supply
name = _tokenName;
// Set the name for display purposes
decimals = _decimalUnits;
// Amount of decimals for display purposes
symbol = _tokenSymbol;
// Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if (!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) {revert();}
return true;
}
}
contract CapitalMiningToken is HumanStandardToken {
/* Public variables of the token */
// Vanity variables
uint256 public simulatedBlockNumber;
uint256 public rewardScarcityFactor; // The factor by which the reward reduces
uint256 public rewardReductionRate; // The number of blocks before the reward reduces
// Reward related variables
uint256 public blockInterval; // Simulate intended blocktime of BitCoin
uint256 public rewardValue; // 50 units, to 8 decimal places
uint256 public initialReward; // Assignment of initial reward
// Payout related variables
mapping (address => Account) public pendingPayouts; // Keep track of per-address contributions in this reward block
mapping (uint => uint) public totalBlockContribution; // Keep track of total ether contribution per block
mapping (uint => bool) public minedBlock; // Checks if block is mined
// contains all variables required to disburse AQT to a contributor fairly
struct Account {
address addr;
uint blockPayout;
uint lastContributionBlockNumber;
uint blockContribution;
}
uint public timeOfLastBlock; // Variable to keep track of when rewards were given
// Constructor
function CapitalMiningToken(string _name, uint8 _decimals, string _symbol, string _version,
uint256 _initialAmount, uint _simulatedBlockNumber, uint _rewardScarcityFactor,
uint _rewardHalveningRate, uint _blockInterval, uint _rewardValue)
HumanStandardToken(_initialAmount, _name, _decimals, _symbol) {
version = _version;
simulatedBlockNumber = _simulatedBlockNumber;
rewardScarcityFactor = _rewardScarcityFactor;
rewardReductionRate = _rewardHalveningRate;
blockInterval = _blockInterval;
rewardValue = _rewardValue;
initialReward = _rewardValue;
timeOfLastBlock = now;
}
// function to call to contribute Ether to, in exchange for AQT in the next block
// mine or updateAccount must be called at least 10 minutes from timeOfLastBlock to get the reward
// minimum required contribution is 0.05 Ether
function mine() payable _updateBlockAndRewardRate() _updateAccount() {
// At this point it is safe to assume that the sender has received all his payouts for previous blocks
require(msg.value >= 50 finney);
totalBlockContribution[simulatedBlockNumber] += msg.value;
// Update total contribution
if (pendingPayouts[msg.sender].addr != msg.sender) {// If the sender has not contributed during this interval
// Add his address and payout details to the contributor map
pendingPayouts[msg.sender] = Account(msg.sender, rewardValue, simulatedBlockNumber,
pendingPayouts[msg.sender].blockContribution + msg.value);
minedBlock[simulatedBlockNumber] = true;
}
else {// the sender has contributed during this interval
require(pendingPayouts[msg.sender].lastContributionBlockNumber == simulatedBlockNumber);
pendingPayouts[msg.sender].blockContribution += msg.value;
}
return;
}
modifier _updateBlockAndRewardRate() {
// Stop update if the time since last block is less than specified interval
if ((now - timeOfLastBlock) >= blockInterval && minedBlock[simulatedBlockNumber] == true) {
timeOfLastBlock = now;
simulatedBlockNumber += 1;
// update reward according to block number
rewardValue = initialReward / (2 ** (simulatedBlockNumber / rewardReductionRate)); // 後で梨沙ちゃんと中本さんに見てもらったほうがいい( ´∀` )
// 毎回毎回計算するよりsimulatedBlockNumber%rewardReductionRateみたいな条件でやったらトランザクションが安くなりそう
}
_;
}
modifier _updateAccount() {
if (pendingPayouts[msg.sender].addr == msg.sender && pendingPayouts[msg.sender].lastContributionBlockNumber < simulatedBlockNumber) {
// もうブロックチェーンにのっているからやり直せないがこれ気持ち悪くない?
uint payout = pendingPayouts[msg.sender].blockContribution * pendingPayouts[msg.sender].blockPayout / totalBlockContribution[pendingPayouts[msg.sender].lastContributionBlockNumber]; // これ分かりづらいから時間あれば分けてやって
pendingPayouts[msg.sender] = Account(0, 0, 0, 0);
// mint coins
totalSupply += payout;
balances[msg.sender] += payout;
// broadcast transfer event to owner
Transfer(0, owner, payout);
// broadcast transfer event from owner to payee
Transfer(owner, msg.sender, payout);
}
_;
}
function updateAccount() _updateBlockAndRewardRate() _updateAccount() {}
function withdrawEther() _onlyOwner() {
owner.transfer(this.balance);
}
}
// This contract defines specific parameters that make the initialized coin Bitcoin-like
contract Aequitas is CapitalMiningToken {
// Constructor
function Aequitas() CapitalMiningToken(
"Aequitas", // name
8, // decimals
"AQT", // symbol
"0.1", // version
0, // initialAmount
0, // simulatedBlockNumber
2, // rewardScarcityFactor
210000, // rewardReductionRate
10 minutes, // blockInterval
5000000000 // rewardValue
){}
} | If the sender has not contributed during this interval
| if (pendingPayouts[msg.sender].addr != msg.sender) { | 1,814,038 | [
1,
2047,
326,
5793,
711,
486,
356,
11050,
4982,
333,
3673,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
261,
9561,
52,
2012,
87,
63,
3576,
18,
15330,
8009,
4793,
480,
1234,
18,
15330,
13,
288,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.18;
pragma experimental ABIEncoderV2;
import "contracts/Allocations.sol";
import "contracts/Proposals.sol";
import "contracts/Utils.sol";
import "contracts/Zipper.sol";
/// @title Exact Dollar Partition base implementation
/// @author Giovanni Rescinito
/// @notice implements the operations required to realize an impartial peer selection according to Exact Dollar Partition
library ExactDollarPartition {
//Events
event QuotasCalculated(uint[] quotas);
event AllocationSelected(uint[] allocation);
event Winners(Utils.Element[] winners);
/// @notice creates a partition of the users consisting in l clusters
/// @param proposals set containing the collected proposals
/// @param l number of clusters to generate
/// @return the zipped partition created, with a row for each cluster
function createPartition(Proposals.Set storage proposals, uint l) view external returns (uint[][] memory){
uint n = Proposals.length(proposals);
uint size = n/l;
uint larger = n%l;
uint[][] memory partition = new uint[][](l);
uint[] memory agents = Utils.range(n);
for (uint i=0; i<l; i++){
uint[] memory tmp;
if (i<larger){
tmp = new uint[](size+1);
}else{
tmp = new uint[](size);
}
for (uint j=i; j<n; j+=l){
tmp[j/l] = agents[j];
}
partition[i] = Zipper.zipArray(tmp,16);
}
return partition;
}
/// @notice generates the assignment according to the rules defined by Exact Dollar Partition
/// @param partition zipped matrix of the clusters in which proposals are divided
/// @param proposals set containing the collected proposals
/// @param m number of reviews to be assigned to each user
function generateAssignments(uint[][] storage partition, Proposals.Set storage proposals, uint m) external {
uint l = partition.length;
uint n = Proposals.length(proposals);
uint[][] memory assignmentsMap = new uint[][](n);
uint[][] memory part = Zipper.unzipMatrix(partition,16);
for (uint i=0;i<l;i++){
require(m <= (n-part[i].length), "Duplicate review required, impossible to create assignments");
}
for (uint i=0;i<l;i++){
uint len = m* part[i].length;
uint[] memory clusterAssignment = new uint[](len);
uint j = 0;
for (uint k=0;k<len;k++){
if (i == j){
j = (j+1)%l;
}
clusterAssignment[k] = j;
j = (j+1)%l;
}
for (j=0;j<part[i].length;j++){
uint[] memory clusters = new uint[](m);
for (uint k = j*m;k<(j+1)*m;k++){
clusters[k%m] = clusterAssignment[k];
}
assignmentsMap[part[i][j]] = clusters;
}
}
uint[] memory indices = new uint[](l);
uint index;
uint[] memory reviewerAssignment = new uint[](m);
for (uint i=0;i<n;i++){
for (uint j=0;j<m;j++){
index = assignmentsMap[i][j];
reviewerAssignment[j] = part[index][indices[index]];
indices[index] = (indices[index] + 1) % part[index].length;
}
Proposals.updateAssignment(proposals, i, reviewerAssignment);
}
}
/// @notice generates integer allocations starting from quotas
/// @param allocations dictionary used to store the possible allocations found
/// @param quotas list of real values representing the expected number of winners from each cluster
function randomizedAllocationFromQuotas(Allocations.Map storage allocations, uint[] memory quotas) external{
uint n = quotas.length;
uint[] memory s = new uint[](n);
uint alpha = 0;
uint i = 0;
for (i=0; i<n; i++){
s[i] = quotas[i] - Utils.floor(quotas[i]);
alpha += s[i];
}
Utils.Element[] memory sSorted = Utils.sort(s);
for (i=0; i<n; i++){
s[i] = quotas[sSorted[i].id];
}
alpha = Utils.round(alpha)/Utils.C;
uint[] memory allocatedProbability = new uint[](n);
uint[] memory allocation = new uint[](n);
uint totalProbability = 0;
uint low = 0;
uint high = n-1;
uint handled = 0;
while (handled <= n){
for (i=0; i<n; i++){
allocation[i] = s[i];
if (i < low){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
}else if ((i >= low) && (i < low + alpha)){
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}else if ((i >= low + alpha) && (i <= high)){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
}else if (i > high){
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}
}
uint p = 0;
if (s[low] - Utils.floor(s[low]) - allocatedProbability[low] < Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high]){
p = s[low] - Utils.floor(s[low]) - allocatedProbability[low];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
low += 1;
}else{
p = Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
high -= 1;
alpha -= 1;
}
totalProbability += p;
Allocations.setAllocation(allocations,allocation,p);
handled += 1;
}
uint[][] memory a;
(a,) = Allocations.getAllocations(allocations);
for (i=0; i<n; i++){
s = new uint[](n);
for (uint j=0; j<n; j++){
s[sSorted[j].id] = a[i][j];
}
Allocations.updateShares(allocations, i, s);
}
}
/// @notice selects an allocation from the dictionary given a random value
/// @param allocations dictionary containing the possible allocations found
/// @param p random value in the range [0,C]
/// @return the winners per cluster from the selected allocation
function selectAllocation(Allocations.Map storage allocations, uint p) view external returns(uint[] memory){
uint i = 0;
uint n = Allocations.length(allocations);
Allocations.Allocation memory a = Allocations.getAllocationAt(allocations,i);
uint currentP = Allocations.getP(a);
while (p>currentP && i < n - 1){
a = Allocations.getAllocationAt(allocations,++i);
currentP += Allocations.getP(a);
}
return Allocations.getShares(a);
}
}
| @title Exact Dollar Partition base implementation @author Giovanni Rescinito @notice implements the operations required to realize an impartial peer selection according to Exact Dollar PartitionEvents | library ExactDollarPartition {
event QuotasCalculated(uint[] quotas);
event AllocationSelected(uint[] allocation);
event Winners(Utils.Element[] winners);
function createPartition(Proposals.Set storage proposals, uint l) view external returns (uint[][] memory){
uint n = Proposals.length(proposals);
uint size = n/l;
uint larger = n%l;
uint[][] memory partition = new uint[][](l);
uint[] memory agents = Utils.range(n);
for (uint i=0; i<l; i++){
uint[] memory tmp;
if (i<larger){
tmp = new uint[](size+1);
tmp = new uint[](size);
}
for (uint j=i; j<n; j+=l){
tmp[j/l] = agents[j];
}
partition[i] = Zipper.zipArray(tmp,16);
}
return partition;
}
function createPartition(Proposals.Set storage proposals, uint l) view external returns (uint[][] memory){
uint n = Proposals.length(proposals);
uint size = n/l;
uint larger = n%l;
uint[][] memory partition = new uint[][](l);
uint[] memory agents = Utils.range(n);
for (uint i=0; i<l; i++){
uint[] memory tmp;
if (i<larger){
tmp = new uint[](size+1);
tmp = new uint[](size);
}
for (uint j=i; j<n; j+=l){
tmp[j/l] = agents[j];
}
partition[i] = Zipper.zipArray(tmp,16);
}
return partition;
}
function createPartition(Proposals.Set storage proposals, uint l) view external returns (uint[][] memory){
uint n = Proposals.length(proposals);
uint size = n/l;
uint larger = n%l;
uint[][] memory partition = new uint[][](l);
uint[] memory agents = Utils.range(n);
for (uint i=0; i<l; i++){
uint[] memory tmp;
if (i<larger){
tmp = new uint[](size+1);
tmp = new uint[](size);
}
for (uint j=i; j<n; j+=l){
tmp[j/l] = agents[j];
}
partition[i] = Zipper.zipArray(tmp,16);
}
return partition;
}
}else{
function createPartition(Proposals.Set storage proposals, uint l) view external returns (uint[][] memory){
uint n = Proposals.length(proposals);
uint size = n/l;
uint larger = n%l;
uint[][] memory partition = new uint[][](l);
uint[] memory agents = Utils.range(n);
for (uint i=0; i<l; i++){
uint[] memory tmp;
if (i<larger){
tmp = new uint[](size+1);
tmp = new uint[](size);
}
for (uint j=i; j<n; j+=l){
tmp[j/l] = agents[j];
}
partition[i] = Zipper.zipArray(tmp,16);
}
return partition;
}
function generateAssignments(uint[][] storage partition, Proposals.Set storage proposals, uint m) external {
uint l = partition.length;
uint n = Proposals.length(proposals);
uint[][] memory assignmentsMap = new uint[][](n);
uint[][] memory part = Zipper.unzipMatrix(partition,16);
for (uint i=0;i<l;i++){
require(m <= (n-part[i].length), "Duplicate review required, impossible to create assignments");
}
for (uint i=0;i<l;i++){
uint len = m* part[i].length;
uint[] memory clusterAssignment = new uint[](len);
uint j = 0;
for (uint k=0;k<len;k++){
if (i == j){
j = (j+1)%l;
}
clusterAssignment[k] = j;
j = (j+1)%l;
}
for (j=0;j<part[i].length;j++){
uint[] memory clusters = new uint[](m);
for (uint k = j*m;k<(j+1)*m;k++){
clusters[k%m] = clusterAssignment[k];
}
assignmentsMap[part[i][j]] = clusters;
}
}
uint[] memory indices = new uint[](l);
uint index;
uint[] memory reviewerAssignment = new uint[](m);
for (uint i=0;i<n;i++){
for (uint j=0;j<m;j++){
index = assignmentsMap[i][j];
reviewerAssignment[j] = part[index][indices[index]];
indices[index] = (indices[index] + 1) % part[index].length;
}
Proposals.updateAssignment(proposals, i, reviewerAssignment);
}
}
function generateAssignments(uint[][] storage partition, Proposals.Set storage proposals, uint m) external {
uint l = partition.length;
uint n = Proposals.length(proposals);
uint[][] memory assignmentsMap = new uint[][](n);
uint[][] memory part = Zipper.unzipMatrix(partition,16);
for (uint i=0;i<l;i++){
require(m <= (n-part[i].length), "Duplicate review required, impossible to create assignments");
}
for (uint i=0;i<l;i++){
uint len = m* part[i].length;
uint[] memory clusterAssignment = new uint[](len);
uint j = 0;
for (uint k=0;k<len;k++){
if (i == j){
j = (j+1)%l;
}
clusterAssignment[k] = j;
j = (j+1)%l;
}
for (j=0;j<part[i].length;j++){
uint[] memory clusters = new uint[](m);
for (uint k = j*m;k<(j+1)*m;k++){
clusters[k%m] = clusterAssignment[k];
}
assignmentsMap[part[i][j]] = clusters;
}
}
uint[] memory indices = new uint[](l);
uint index;
uint[] memory reviewerAssignment = new uint[](m);
for (uint i=0;i<n;i++){
for (uint j=0;j<m;j++){
index = assignmentsMap[i][j];
reviewerAssignment[j] = part[index][indices[index]];
indices[index] = (indices[index] + 1) % part[index].length;
}
Proposals.updateAssignment(proposals, i, reviewerAssignment);
}
}
function generateAssignments(uint[][] storage partition, Proposals.Set storage proposals, uint m) external {
uint l = partition.length;
uint n = Proposals.length(proposals);
uint[][] memory assignmentsMap = new uint[][](n);
uint[][] memory part = Zipper.unzipMatrix(partition,16);
for (uint i=0;i<l;i++){
require(m <= (n-part[i].length), "Duplicate review required, impossible to create assignments");
}
for (uint i=0;i<l;i++){
uint len = m* part[i].length;
uint[] memory clusterAssignment = new uint[](len);
uint j = 0;
for (uint k=0;k<len;k++){
if (i == j){
j = (j+1)%l;
}
clusterAssignment[k] = j;
j = (j+1)%l;
}
for (j=0;j<part[i].length;j++){
uint[] memory clusters = new uint[](m);
for (uint k = j*m;k<(j+1)*m;k++){
clusters[k%m] = clusterAssignment[k];
}
assignmentsMap[part[i][j]] = clusters;
}
}
uint[] memory indices = new uint[](l);
uint index;
uint[] memory reviewerAssignment = new uint[](m);
for (uint i=0;i<n;i++){
for (uint j=0;j<m;j++){
index = assignmentsMap[i][j];
reviewerAssignment[j] = part[index][indices[index]];
indices[index] = (indices[index] + 1) % part[index].length;
}
Proposals.updateAssignment(proposals, i, reviewerAssignment);
}
}
function generateAssignments(uint[][] storage partition, Proposals.Set storage proposals, uint m) external {
uint l = partition.length;
uint n = Proposals.length(proposals);
uint[][] memory assignmentsMap = new uint[][](n);
uint[][] memory part = Zipper.unzipMatrix(partition,16);
for (uint i=0;i<l;i++){
require(m <= (n-part[i].length), "Duplicate review required, impossible to create assignments");
}
for (uint i=0;i<l;i++){
uint len = m* part[i].length;
uint[] memory clusterAssignment = new uint[](len);
uint j = 0;
for (uint k=0;k<len;k++){
if (i == j){
j = (j+1)%l;
}
clusterAssignment[k] = j;
j = (j+1)%l;
}
for (j=0;j<part[i].length;j++){
uint[] memory clusters = new uint[](m);
for (uint k = j*m;k<(j+1)*m;k++){
clusters[k%m] = clusterAssignment[k];
}
assignmentsMap[part[i][j]] = clusters;
}
}
uint[] memory indices = new uint[](l);
uint index;
uint[] memory reviewerAssignment = new uint[](m);
for (uint i=0;i<n;i++){
for (uint j=0;j<m;j++){
index = assignmentsMap[i][j];
reviewerAssignment[j] = part[index][indices[index]];
indices[index] = (indices[index] + 1) % part[index].length;
}
Proposals.updateAssignment(proposals, i, reviewerAssignment);
}
}
function generateAssignments(uint[][] storage partition, Proposals.Set storage proposals, uint m) external {
uint l = partition.length;
uint n = Proposals.length(proposals);
uint[][] memory assignmentsMap = new uint[][](n);
uint[][] memory part = Zipper.unzipMatrix(partition,16);
for (uint i=0;i<l;i++){
require(m <= (n-part[i].length), "Duplicate review required, impossible to create assignments");
}
for (uint i=0;i<l;i++){
uint len = m* part[i].length;
uint[] memory clusterAssignment = new uint[](len);
uint j = 0;
for (uint k=0;k<len;k++){
if (i == j){
j = (j+1)%l;
}
clusterAssignment[k] = j;
j = (j+1)%l;
}
for (j=0;j<part[i].length;j++){
uint[] memory clusters = new uint[](m);
for (uint k = j*m;k<(j+1)*m;k++){
clusters[k%m] = clusterAssignment[k];
}
assignmentsMap[part[i][j]] = clusters;
}
}
uint[] memory indices = new uint[](l);
uint index;
uint[] memory reviewerAssignment = new uint[](m);
for (uint i=0;i<n;i++){
for (uint j=0;j<m;j++){
index = assignmentsMap[i][j];
reviewerAssignment[j] = part[index][indices[index]];
indices[index] = (indices[index] + 1) % part[index].length;
}
Proposals.updateAssignment(proposals, i, reviewerAssignment);
}
}
function generateAssignments(uint[][] storage partition, Proposals.Set storage proposals, uint m) external {
uint l = partition.length;
uint n = Proposals.length(proposals);
uint[][] memory assignmentsMap = new uint[][](n);
uint[][] memory part = Zipper.unzipMatrix(partition,16);
for (uint i=0;i<l;i++){
require(m <= (n-part[i].length), "Duplicate review required, impossible to create assignments");
}
for (uint i=0;i<l;i++){
uint len = m* part[i].length;
uint[] memory clusterAssignment = new uint[](len);
uint j = 0;
for (uint k=0;k<len;k++){
if (i == j){
j = (j+1)%l;
}
clusterAssignment[k] = j;
j = (j+1)%l;
}
for (j=0;j<part[i].length;j++){
uint[] memory clusters = new uint[](m);
for (uint k = j*m;k<(j+1)*m;k++){
clusters[k%m] = clusterAssignment[k];
}
assignmentsMap[part[i][j]] = clusters;
}
}
uint[] memory indices = new uint[](l);
uint index;
uint[] memory reviewerAssignment = new uint[](m);
for (uint i=0;i<n;i++){
for (uint j=0;j<m;j++){
index = assignmentsMap[i][j];
reviewerAssignment[j] = part[index][indices[index]];
indices[index] = (indices[index] + 1) % part[index].length;
}
Proposals.updateAssignment(proposals, i, reviewerAssignment);
}
}
function generateAssignments(uint[][] storage partition, Proposals.Set storage proposals, uint m) external {
uint l = partition.length;
uint n = Proposals.length(proposals);
uint[][] memory assignmentsMap = new uint[][](n);
uint[][] memory part = Zipper.unzipMatrix(partition,16);
for (uint i=0;i<l;i++){
require(m <= (n-part[i].length), "Duplicate review required, impossible to create assignments");
}
for (uint i=0;i<l;i++){
uint len = m* part[i].length;
uint[] memory clusterAssignment = new uint[](len);
uint j = 0;
for (uint k=0;k<len;k++){
if (i == j){
j = (j+1)%l;
}
clusterAssignment[k] = j;
j = (j+1)%l;
}
for (j=0;j<part[i].length;j++){
uint[] memory clusters = new uint[](m);
for (uint k = j*m;k<(j+1)*m;k++){
clusters[k%m] = clusterAssignment[k];
}
assignmentsMap[part[i][j]] = clusters;
}
}
uint[] memory indices = new uint[](l);
uint index;
uint[] memory reviewerAssignment = new uint[](m);
for (uint i=0;i<n;i++){
for (uint j=0;j<m;j++){
index = assignmentsMap[i][j];
reviewerAssignment[j] = part[index][indices[index]];
indices[index] = (indices[index] + 1) % part[index].length;
}
Proposals.updateAssignment(proposals, i, reviewerAssignment);
}
}
function generateAssignments(uint[][] storage partition, Proposals.Set storage proposals, uint m) external {
uint l = partition.length;
uint n = Proposals.length(proposals);
uint[][] memory assignmentsMap = new uint[][](n);
uint[][] memory part = Zipper.unzipMatrix(partition,16);
for (uint i=0;i<l;i++){
require(m <= (n-part[i].length), "Duplicate review required, impossible to create assignments");
}
for (uint i=0;i<l;i++){
uint len = m* part[i].length;
uint[] memory clusterAssignment = new uint[](len);
uint j = 0;
for (uint k=0;k<len;k++){
if (i == j){
j = (j+1)%l;
}
clusterAssignment[k] = j;
j = (j+1)%l;
}
for (j=0;j<part[i].length;j++){
uint[] memory clusters = new uint[](m);
for (uint k = j*m;k<(j+1)*m;k++){
clusters[k%m] = clusterAssignment[k];
}
assignmentsMap[part[i][j]] = clusters;
}
}
uint[] memory indices = new uint[](l);
uint index;
uint[] memory reviewerAssignment = new uint[](m);
for (uint i=0;i<n;i++){
for (uint j=0;j<m;j++){
index = assignmentsMap[i][j];
reviewerAssignment[j] = part[index][indices[index]];
indices[index] = (indices[index] + 1) % part[index].length;
}
Proposals.updateAssignment(proposals, i, reviewerAssignment);
}
}
function generateAssignments(uint[][] storage partition, Proposals.Set storage proposals, uint m) external {
uint l = partition.length;
uint n = Proposals.length(proposals);
uint[][] memory assignmentsMap = new uint[][](n);
uint[][] memory part = Zipper.unzipMatrix(partition,16);
for (uint i=0;i<l;i++){
require(m <= (n-part[i].length), "Duplicate review required, impossible to create assignments");
}
for (uint i=0;i<l;i++){
uint len = m* part[i].length;
uint[] memory clusterAssignment = new uint[](len);
uint j = 0;
for (uint k=0;k<len;k++){
if (i == j){
j = (j+1)%l;
}
clusterAssignment[k] = j;
j = (j+1)%l;
}
for (j=0;j<part[i].length;j++){
uint[] memory clusters = new uint[](m);
for (uint k = j*m;k<(j+1)*m;k++){
clusters[k%m] = clusterAssignment[k];
}
assignmentsMap[part[i][j]] = clusters;
}
}
uint[] memory indices = new uint[](l);
uint index;
uint[] memory reviewerAssignment = new uint[](m);
for (uint i=0;i<n;i++){
for (uint j=0;j<m;j++){
index = assignmentsMap[i][j];
reviewerAssignment[j] = part[index][indices[index]];
indices[index] = (indices[index] + 1) % part[index].length;
}
Proposals.updateAssignment(proposals, i, reviewerAssignment);
}
}
function randomizedAllocationFromQuotas(Allocations.Map storage allocations, uint[] memory quotas) external{
uint n = quotas.length;
uint[] memory s = new uint[](n);
uint alpha = 0;
uint i = 0;
for (i=0; i<n; i++){
s[i] = quotas[i] - Utils.floor(quotas[i]);
alpha += s[i];
}
Utils.Element[] memory sSorted = Utils.sort(s);
for (i=0; i<n; i++){
s[i] = quotas[sSorted[i].id];
}
alpha = Utils.round(alpha)/Utils.C;
uint[] memory allocatedProbability = new uint[](n);
uint[] memory allocation = new uint[](n);
uint totalProbability = 0;
uint low = 0;
uint high = n-1;
uint handled = 0;
while (handled <= n){
for (i=0; i<n; i++){
allocation[i] = s[i];
if (i < low){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}
}
uint p = 0;
if (s[low] - Utils.floor(s[low]) - allocatedProbability[low] < Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high]){
p = s[low] - Utils.floor(s[low]) - allocatedProbability[low];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
low += 1;
p = Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
high -= 1;
alpha -= 1;
}
totalProbability += p;
Allocations.setAllocation(allocations,allocation,p);
handled += 1;
}
uint[][] memory a;
(a,) = Allocations.getAllocations(allocations);
for (i=0; i<n; i++){
s = new uint[](n);
for (uint j=0; j<n; j++){
s[sSorted[j].id] = a[i][j];
}
Allocations.updateShares(allocations, i, s);
}
}
function randomizedAllocationFromQuotas(Allocations.Map storage allocations, uint[] memory quotas) external{
uint n = quotas.length;
uint[] memory s = new uint[](n);
uint alpha = 0;
uint i = 0;
for (i=0; i<n; i++){
s[i] = quotas[i] - Utils.floor(quotas[i]);
alpha += s[i];
}
Utils.Element[] memory sSorted = Utils.sort(s);
for (i=0; i<n; i++){
s[i] = quotas[sSorted[i].id];
}
alpha = Utils.round(alpha)/Utils.C;
uint[] memory allocatedProbability = new uint[](n);
uint[] memory allocation = new uint[](n);
uint totalProbability = 0;
uint low = 0;
uint high = n-1;
uint handled = 0;
while (handled <= n){
for (i=0; i<n; i++){
allocation[i] = s[i];
if (i < low){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}
}
uint p = 0;
if (s[low] - Utils.floor(s[low]) - allocatedProbability[low] < Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high]){
p = s[low] - Utils.floor(s[low]) - allocatedProbability[low];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
low += 1;
p = Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
high -= 1;
alpha -= 1;
}
totalProbability += p;
Allocations.setAllocation(allocations,allocation,p);
handled += 1;
}
uint[][] memory a;
(a,) = Allocations.getAllocations(allocations);
for (i=0; i<n; i++){
s = new uint[](n);
for (uint j=0; j<n; j++){
s[sSorted[j].id] = a[i][j];
}
Allocations.updateShares(allocations, i, s);
}
}
function randomizedAllocationFromQuotas(Allocations.Map storage allocations, uint[] memory quotas) external{
uint n = quotas.length;
uint[] memory s = new uint[](n);
uint alpha = 0;
uint i = 0;
for (i=0; i<n; i++){
s[i] = quotas[i] - Utils.floor(quotas[i]);
alpha += s[i];
}
Utils.Element[] memory sSorted = Utils.sort(s);
for (i=0; i<n; i++){
s[i] = quotas[sSorted[i].id];
}
alpha = Utils.round(alpha)/Utils.C;
uint[] memory allocatedProbability = new uint[](n);
uint[] memory allocation = new uint[](n);
uint totalProbability = 0;
uint low = 0;
uint high = n-1;
uint handled = 0;
while (handled <= n){
for (i=0; i<n; i++){
allocation[i] = s[i];
if (i < low){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}
}
uint p = 0;
if (s[low] - Utils.floor(s[low]) - allocatedProbability[low] < Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high]){
p = s[low] - Utils.floor(s[low]) - allocatedProbability[low];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
low += 1;
p = Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
high -= 1;
alpha -= 1;
}
totalProbability += p;
Allocations.setAllocation(allocations,allocation,p);
handled += 1;
}
uint[][] memory a;
(a,) = Allocations.getAllocations(allocations);
for (i=0; i<n; i++){
s = new uint[](n);
for (uint j=0; j<n; j++){
s[sSorted[j].id] = a[i][j];
}
Allocations.updateShares(allocations, i, s);
}
}
function randomizedAllocationFromQuotas(Allocations.Map storage allocations, uint[] memory quotas) external{
uint n = quotas.length;
uint[] memory s = new uint[](n);
uint alpha = 0;
uint i = 0;
for (i=0; i<n; i++){
s[i] = quotas[i] - Utils.floor(quotas[i]);
alpha += s[i];
}
Utils.Element[] memory sSorted = Utils.sort(s);
for (i=0; i<n; i++){
s[i] = quotas[sSorted[i].id];
}
alpha = Utils.round(alpha)/Utils.C;
uint[] memory allocatedProbability = new uint[](n);
uint[] memory allocation = new uint[](n);
uint totalProbability = 0;
uint low = 0;
uint high = n-1;
uint handled = 0;
while (handled <= n){
for (i=0; i<n; i++){
allocation[i] = s[i];
if (i < low){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}
}
uint p = 0;
if (s[low] - Utils.floor(s[low]) - allocatedProbability[low] < Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high]){
p = s[low] - Utils.floor(s[low]) - allocatedProbability[low];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
low += 1;
p = Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
high -= 1;
alpha -= 1;
}
totalProbability += p;
Allocations.setAllocation(allocations,allocation,p);
handled += 1;
}
uint[][] memory a;
(a,) = Allocations.getAllocations(allocations);
for (i=0; i<n; i++){
s = new uint[](n);
for (uint j=0; j<n; j++){
s[sSorted[j].id] = a[i][j];
}
Allocations.updateShares(allocations, i, s);
}
}
function randomizedAllocationFromQuotas(Allocations.Map storage allocations, uint[] memory quotas) external{
uint n = quotas.length;
uint[] memory s = new uint[](n);
uint alpha = 0;
uint i = 0;
for (i=0; i<n; i++){
s[i] = quotas[i] - Utils.floor(quotas[i]);
alpha += s[i];
}
Utils.Element[] memory sSorted = Utils.sort(s);
for (i=0; i<n; i++){
s[i] = quotas[sSorted[i].id];
}
alpha = Utils.round(alpha)/Utils.C;
uint[] memory allocatedProbability = new uint[](n);
uint[] memory allocation = new uint[](n);
uint totalProbability = 0;
uint low = 0;
uint high = n-1;
uint handled = 0;
while (handled <= n){
for (i=0; i<n; i++){
allocation[i] = s[i];
if (i < low){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}
}
uint p = 0;
if (s[low] - Utils.floor(s[low]) - allocatedProbability[low] < Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high]){
p = s[low] - Utils.floor(s[low]) - allocatedProbability[low];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
low += 1;
p = Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
high -= 1;
alpha -= 1;
}
totalProbability += p;
Allocations.setAllocation(allocations,allocation,p);
handled += 1;
}
uint[][] memory a;
(a,) = Allocations.getAllocations(allocations);
for (i=0; i<n; i++){
s = new uint[](n);
for (uint j=0; j<n; j++){
s[sSorted[j].id] = a[i][j];
}
Allocations.updateShares(allocations, i, s);
}
}
function randomizedAllocationFromQuotas(Allocations.Map storage allocations, uint[] memory quotas) external{
uint n = quotas.length;
uint[] memory s = new uint[](n);
uint alpha = 0;
uint i = 0;
for (i=0; i<n; i++){
s[i] = quotas[i] - Utils.floor(quotas[i]);
alpha += s[i];
}
Utils.Element[] memory sSorted = Utils.sort(s);
for (i=0; i<n; i++){
s[i] = quotas[sSorted[i].id];
}
alpha = Utils.round(alpha)/Utils.C;
uint[] memory allocatedProbability = new uint[](n);
uint[] memory allocation = new uint[](n);
uint totalProbability = 0;
uint low = 0;
uint high = n-1;
uint handled = 0;
while (handled <= n){
for (i=0; i<n; i++){
allocation[i] = s[i];
if (i < low){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}
}
uint p = 0;
if (s[low] - Utils.floor(s[low]) - allocatedProbability[low] < Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high]){
p = s[low] - Utils.floor(s[low]) - allocatedProbability[low];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
low += 1;
p = Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
high -= 1;
alpha -= 1;
}
totalProbability += p;
Allocations.setAllocation(allocations,allocation,p);
handled += 1;
}
uint[][] memory a;
(a,) = Allocations.getAllocations(allocations);
for (i=0; i<n; i++){
s = new uint[](n);
for (uint j=0; j<n; j++){
s[sSorted[j].id] = a[i][j];
}
Allocations.updateShares(allocations, i, s);
}
}
}else if ((i >= low) && (i < low + alpha)){
}else if ((i >= low + alpha) && (i <= high)){
}else if (i > high){
function randomizedAllocationFromQuotas(Allocations.Map storage allocations, uint[] memory quotas) external{
uint n = quotas.length;
uint[] memory s = new uint[](n);
uint alpha = 0;
uint i = 0;
for (i=0; i<n; i++){
s[i] = quotas[i] - Utils.floor(quotas[i]);
alpha += s[i];
}
Utils.Element[] memory sSorted = Utils.sort(s);
for (i=0; i<n; i++){
s[i] = quotas[sSorted[i].id];
}
alpha = Utils.round(alpha)/Utils.C;
uint[] memory allocatedProbability = new uint[](n);
uint[] memory allocation = new uint[](n);
uint totalProbability = 0;
uint low = 0;
uint high = n-1;
uint handled = 0;
while (handled <= n){
for (i=0; i<n; i++){
allocation[i] = s[i];
if (i < low){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}
}
uint p = 0;
if (s[low] - Utils.floor(s[low]) - allocatedProbability[low] < Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high]){
p = s[low] - Utils.floor(s[low]) - allocatedProbability[low];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
low += 1;
p = Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
high -= 1;
alpha -= 1;
}
totalProbability += p;
Allocations.setAllocation(allocations,allocation,p);
handled += 1;
}
uint[][] memory a;
(a,) = Allocations.getAllocations(allocations);
for (i=0; i<n; i++){
s = new uint[](n);
for (uint j=0; j<n; j++){
s[sSorted[j].id] = a[i][j];
}
Allocations.updateShares(allocations, i, s);
}
}
function randomizedAllocationFromQuotas(Allocations.Map storage allocations, uint[] memory quotas) external{
uint n = quotas.length;
uint[] memory s = new uint[](n);
uint alpha = 0;
uint i = 0;
for (i=0; i<n; i++){
s[i] = quotas[i] - Utils.floor(quotas[i]);
alpha += s[i];
}
Utils.Element[] memory sSorted = Utils.sort(s);
for (i=0; i<n; i++){
s[i] = quotas[sSorted[i].id];
}
alpha = Utils.round(alpha)/Utils.C;
uint[] memory allocatedProbability = new uint[](n);
uint[] memory allocation = new uint[](n);
uint totalProbability = 0;
uint low = 0;
uint high = n-1;
uint handled = 0;
while (handled <= n){
for (i=0; i<n; i++){
allocation[i] = s[i];
if (i < low){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}
}
uint p = 0;
if (s[low] - Utils.floor(s[low]) - allocatedProbability[low] < Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high]){
p = s[low] - Utils.floor(s[low]) - allocatedProbability[low];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
low += 1;
p = Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
high -= 1;
alpha -= 1;
}
totalProbability += p;
Allocations.setAllocation(allocations,allocation,p);
handled += 1;
}
uint[][] memory a;
(a,) = Allocations.getAllocations(allocations);
for (i=0; i<n; i++){
s = new uint[](n);
for (uint j=0; j<n; j++){
s[sSorted[j].id] = a[i][j];
}
Allocations.updateShares(allocations, i, s);
}
}
function randomizedAllocationFromQuotas(Allocations.Map storage allocations, uint[] memory quotas) external{
uint n = quotas.length;
uint[] memory s = new uint[](n);
uint alpha = 0;
uint i = 0;
for (i=0; i<n; i++){
s[i] = quotas[i] - Utils.floor(quotas[i]);
alpha += s[i];
}
Utils.Element[] memory sSorted = Utils.sort(s);
for (i=0; i<n; i++){
s[i] = quotas[sSorted[i].id];
}
alpha = Utils.round(alpha)/Utils.C;
uint[] memory allocatedProbability = new uint[](n);
uint[] memory allocation = new uint[](n);
uint totalProbability = 0;
uint low = 0;
uint high = n-1;
uint handled = 0;
while (handled <= n){
for (i=0; i<n; i++){
allocation[i] = s[i];
if (i < low){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}
}
uint p = 0;
if (s[low] - Utils.floor(s[low]) - allocatedProbability[low] < Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high]){
p = s[low] - Utils.floor(s[low]) - allocatedProbability[low];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
low += 1;
p = Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
high -= 1;
alpha -= 1;
}
totalProbability += p;
Allocations.setAllocation(allocations,allocation,p);
handled += 1;
}
uint[][] memory a;
(a,) = Allocations.getAllocations(allocations);
for (i=0; i<n; i++){
s = new uint[](n);
for (uint j=0; j<n; j++){
s[sSorted[j].id] = a[i][j];
}
Allocations.updateShares(allocations, i, s);
}
}
function randomizedAllocationFromQuotas(Allocations.Map storage allocations, uint[] memory quotas) external{
uint n = quotas.length;
uint[] memory s = new uint[](n);
uint alpha = 0;
uint i = 0;
for (i=0; i<n; i++){
s[i] = quotas[i] - Utils.floor(quotas[i]);
alpha += s[i];
}
Utils.Element[] memory sSorted = Utils.sort(s);
for (i=0; i<n; i++){
s[i] = quotas[sSorted[i].id];
}
alpha = Utils.round(alpha)/Utils.C;
uint[] memory allocatedProbability = new uint[](n);
uint[] memory allocation = new uint[](n);
uint totalProbability = 0;
uint low = 0;
uint high = n-1;
uint handled = 0;
while (handled <= n){
for (i=0; i<n; i++){
allocation[i] = s[i];
if (i < low){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}
}
uint p = 0;
if (s[low] - Utils.floor(s[low]) - allocatedProbability[low] < Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high]){
p = s[low] - Utils.floor(s[low]) - allocatedProbability[low];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
low += 1;
p = Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
high -= 1;
alpha -= 1;
}
totalProbability += p;
Allocations.setAllocation(allocations,allocation,p);
handled += 1;
}
uint[][] memory a;
(a,) = Allocations.getAllocations(allocations);
for (i=0; i<n; i++){
s = new uint[](n);
for (uint j=0; j<n; j++){
s[sSorted[j].id] = a[i][j];
}
Allocations.updateShares(allocations, i, s);
}
}
}else{
function randomizedAllocationFromQuotas(Allocations.Map storage allocations, uint[] memory quotas) external{
uint n = quotas.length;
uint[] memory s = new uint[](n);
uint alpha = 0;
uint i = 0;
for (i=0; i<n; i++){
s[i] = quotas[i] - Utils.floor(quotas[i]);
alpha += s[i];
}
Utils.Element[] memory sSorted = Utils.sort(s);
for (i=0; i<n; i++){
s[i] = quotas[sSorted[i].id];
}
alpha = Utils.round(alpha)/Utils.C;
uint[] memory allocatedProbability = new uint[](n);
uint[] memory allocation = new uint[](n);
uint totalProbability = 0;
uint low = 0;
uint high = n-1;
uint handled = 0;
while (handled <= n){
for (i=0; i<n; i++){
allocation[i] = s[i];
if (i < low){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}
}
uint p = 0;
if (s[low] - Utils.floor(s[low]) - allocatedProbability[low] < Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high]){
p = s[low] - Utils.floor(s[low]) - allocatedProbability[low];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
low += 1;
p = Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
high -= 1;
alpha -= 1;
}
totalProbability += p;
Allocations.setAllocation(allocations,allocation,p);
handled += 1;
}
uint[][] memory a;
(a,) = Allocations.getAllocations(allocations);
for (i=0; i<n; i++){
s = new uint[](n);
for (uint j=0; j<n; j++){
s[sSorted[j].id] = a[i][j];
}
Allocations.updateShares(allocations, i, s);
}
}
function randomizedAllocationFromQuotas(Allocations.Map storage allocations, uint[] memory quotas) external{
uint n = quotas.length;
uint[] memory s = new uint[](n);
uint alpha = 0;
uint i = 0;
for (i=0; i<n; i++){
s[i] = quotas[i] - Utils.floor(quotas[i]);
alpha += s[i];
}
Utils.Element[] memory sSorted = Utils.sort(s);
for (i=0; i<n; i++){
s[i] = quotas[sSorted[i].id];
}
alpha = Utils.round(alpha)/Utils.C;
uint[] memory allocatedProbability = new uint[](n);
uint[] memory allocation = new uint[](n);
uint totalProbability = 0;
uint low = 0;
uint high = n-1;
uint handled = 0;
while (handled <= n){
for (i=0; i<n; i++){
allocation[i] = s[i];
if (i < low){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}
}
uint p = 0;
if (s[low] - Utils.floor(s[low]) - allocatedProbability[low] < Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high]){
p = s[low] - Utils.floor(s[low]) - allocatedProbability[low];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
low += 1;
p = Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
high -= 1;
alpha -= 1;
}
totalProbability += p;
Allocations.setAllocation(allocations,allocation,p);
handled += 1;
}
uint[][] memory a;
(a,) = Allocations.getAllocations(allocations);
for (i=0; i<n; i++){
s = new uint[](n);
for (uint j=0; j<n; j++){
s[sSorted[j].id] = a[i][j];
}
Allocations.updateShares(allocations, i, s);
}
}
function randomizedAllocationFromQuotas(Allocations.Map storage allocations, uint[] memory quotas) external{
uint n = quotas.length;
uint[] memory s = new uint[](n);
uint alpha = 0;
uint i = 0;
for (i=0; i<n; i++){
s[i] = quotas[i] - Utils.floor(quotas[i]);
alpha += s[i];
}
Utils.Element[] memory sSorted = Utils.sort(s);
for (i=0; i<n; i++){
s[i] = quotas[sSorted[i].id];
}
alpha = Utils.round(alpha)/Utils.C;
uint[] memory allocatedProbability = new uint[](n);
uint[] memory allocation = new uint[](n);
uint totalProbability = 0;
uint low = 0;
uint high = n-1;
uint handled = 0;
while (handled <= n){
for (i=0; i<n; i++){
allocation[i] = s[i];
if (i < low){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}
}
uint p = 0;
if (s[low] - Utils.floor(s[low]) - allocatedProbability[low] < Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high]){
p = s[low] - Utils.floor(s[low]) - allocatedProbability[low];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
low += 1;
p = Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
high -= 1;
alpha -= 1;
}
totalProbability += p;
Allocations.setAllocation(allocations,allocation,p);
handled += 1;
}
uint[][] memory a;
(a,) = Allocations.getAllocations(allocations);
for (i=0; i<n; i++){
s = new uint[](n);
for (uint j=0; j<n; j++){
s[sSorted[j].id] = a[i][j];
}
Allocations.updateShares(allocations, i, s);
}
}
function randomizedAllocationFromQuotas(Allocations.Map storage allocations, uint[] memory quotas) external{
uint n = quotas.length;
uint[] memory s = new uint[](n);
uint alpha = 0;
uint i = 0;
for (i=0; i<n; i++){
s[i] = quotas[i] - Utils.floor(quotas[i]);
alpha += s[i];
}
Utils.Element[] memory sSorted = Utils.sort(s);
for (i=0; i<n; i++){
s[i] = quotas[sSorted[i].id];
}
alpha = Utils.round(alpha)/Utils.C;
uint[] memory allocatedProbability = new uint[](n);
uint[] memory allocation = new uint[](n);
uint totalProbability = 0;
uint low = 0;
uint high = n-1;
uint handled = 0;
while (handled <= n){
for (i=0; i<n; i++){
allocation[i] = s[i];
if (i < low){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}
}
uint p = 0;
if (s[low] - Utils.floor(s[low]) - allocatedProbability[low] < Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high]){
p = s[low] - Utils.floor(s[low]) - allocatedProbability[low];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
low += 1;
p = Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
high -= 1;
alpha -= 1;
}
totalProbability += p;
Allocations.setAllocation(allocations,allocation,p);
handled += 1;
}
uint[][] memory a;
(a,) = Allocations.getAllocations(allocations);
for (i=0; i<n; i++){
s = new uint[](n);
for (uint j=0; j<n; j++){
s[sSorted[j].id] = a[i][j];
}
Allocations.updateShares(allocations, i, s);
}
}
function randomizedAllocationFromQuotas(Allocations.Map storage allocations, uint[] memory quotas) external{
uint n = quotas.length;
uint[] memory s = new uint[](n);
uint alpha = 0;
uint i = 0;
for (i=0; i<n; i++){
s[i] = quotas[i] - Utils.floor(quotas[i]);
alpha += s[i];
}
Utils.Element[] memory sSorted = Utils.sort(s);
for (i=0; i<n; i++){
s[i] = quotas[sSorted[i].id];
}
alpha = Utils.round(alpha)/Utils.C;
uint[] memory allocatedProbability = new uint[](n);
uint[] memory allocation = new uint[](n);
uint totalProbability = 0;
uint low = 0;
uint high = n-1;
uint handled = 0;
while (handled <= n){
for (i=0; i<n; i++){
allocation[i] = s[i];
if (i < low){
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
allocation[i] = Utils.floor(allocation[i])/Utils.C;
allocation[i] = Utils.ceil(allocation[i])/Utils.C;
}
}
uint p = 0;
if (s[low] - Utils.floor(s[low]) - allocatedProbability[low] < Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high]){
p = s[low] - Utils.floor(s[low]) - allocatedProbability[low];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
low += 1;
p = Utils.ceil(s[high]) - s[high] - totalProbability + allocatedProbability[high];
for (i=0; i<n; i++){
if (i >= low && i < low + alpha){
allocatedProbability[i] += p;
}
if (i > high){
allocatedProbability[i] += p;
}
}
high -= 1;
alpha -= 1;
}
totalProbability += p;
Allocations.setAllocation(allocations,allocation,p);
handled += 1;
}
uint[][] memory a;
(a,) = Allocations.getAllocations(allocations);
for (i=0; i<n; i++){
s = new uint[](n);
for (uint j=0; j<n; j++){
s[sSorted[j].id] = a[i][j];
}
Allocations.updateShares(allocations, i, s);
}
}
function selectAllocation(Allocations.Map storage allocations, uint p) view external returns(uint[] memory){
uint i = 0;
uint n = Allocations.length(allocations);
Allocations.Allocation memory a = Allocations.getAllocationAt(allocations,i);
uint currentP = Allocations.getP(a);
while (p>currentP && i < n - 1){
a = Allocations.getAllocationAt(allocations,++i);
currentP += Allocations.getP(a);
}
return Allocations.getShares(a);
}
function selectAllocation(Allocations.Map storage allocations, uint p) view external returns(uint[] memory){
uint i = 0;
uint n = Allocations.length(allocations);
Allocations.Allocation memory a = Allocations.getAllocationAt(allocations,i);
uint currentP = Allocations.getP(a);
while (p>currentP && i < n - 1){
a = Allocations.getAllocationAt(allocations,++i);
currentP += Allocations.getP(a);
}
return Allocations.getShares(a);
}
}
| 14,028,150 | [
1,
14332,
463,
25442,
12598,
1026,
4471,
225,
611,
77,
1527,
1072,
77,
534,
742,
2738,
83,
225,
4792,
326,
5295,
1931,
358,
2863,
554,
392,
1646,
485,
649,
4261,
4421,
4888,
358,
30794,
463,
25442,
12598,
3783,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
30794,
40,
25442,
7003,
288,
203,
203,
565,
871,
4783,
352,
345,
4844,
690,
12,
11890,
8526,
4914,
345,
1769,
203,
565,
871,
24242,
7416,
12,
11890,
8526,
13481,
1769,
203,
565,
871,
21628,
9646,
12,
1989,
18,
1046,
8526,
5657,
9646,
1769,
203,
377,
203,
203,
565,
445,
752,
7003,
12,
626,
22536,
18,
694,
2502,
450,
22536,
16,
225,
2254,
328,
13,
1476,
3903,
1135,
261,
11890,
63,
6362,
65,
3778,
15329,
203,
3639,
2254,
290,
273,
1186,
22536,
18,
2469,
12,
685,
22536,
1769,
203,
3639,
2254,
963,
273,
290,
19,
80,
31,
203,
3639,
2254,
10974,
273,
290,
9,
80,
31,
203,
3639,
2254,
63,
6362,
65,
3778,
3590,
273,
394,
2254,
63,
6362,
29955,
80,
1769,
203,
3639,
2254,
8526,
3778,
16423,
273,
6091,
18,
3676,
12,
82,
1769,
203,
3639,
364,
261,
11890,
277,
33,
20,
31,
277,
32,
80,
31,
277,
27245,
95,
203,
5411,
2254,
8526,
3778,
1853,
31,
203,
5411,
309,
261,
77,
32,
7901,
693,
15329,
203,
7734,
1853,
273,
394,
2254,
8526,
12,
1467,
15,
21,
1769,
203,
7734,
1853,
273,
394,
2254,
8526,
12,
1467,
1769,
203,
5411,
289,
203,
5411,
364,
261,
11890,
525,
33,
77,
31,
525,
32,
82,
31,
525,
15,
33,
80,
15329,
203,
7734,
1853,
63,
78,
19,
80,
65,
273,
16423,
63,
78,
15533,
203,
5411,
289,
203,
5411,
3590,
63,
77,
65,
273,
8603,
457,
18,
4450,
1076,
12,
5645,
16,
2313,
1769,
203,
3639,
289,
203,
3639,
327,
3590,
31,
203,
565,
289,
2
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IUniswapV2Router02} from "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Router02.sol";
import {IUniswapV2Pair} from "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import {UniswapV2Library} from "@sushiswap/core/contracts/uniswapv2/libraries/UniswapV2Library.sol";
import {IMiniChefV2} from "./interfaces/IMiniChefV2.sol";
import {IWrappedToken} from "./interfaces/IWrappedToken.sol";
import {Farmer} from "./Farmer.sol";
/// @title SushiFarmer is a contract which helps with managing a farming position on
/// Sushiswap. Its main purpose is to automate compounding of your positions. That is,
/// taking the reward(s) earned through staking and swapping these for the underlying
/// assets of your LP position and swapping these for more LP tokens and compounding
/// your position.
/// @author 0xdavinchee
contract SushiFarmer is
Farmer(IUniswapV2Router02(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506))
{
IMiniChefV2 public chef;
IERC20 public rewardTokenA;
IERC20 public rewardTokenB; // if hasNativeReward, this should be wrapped token addr
uint256 public rewardASavingsRate = 0;
uint256 public rewardBSavingsRate = 0;
bool public hasNativeReward;
constructor(
IMiniChefV2 _chef,
IERC20 _rewardTokenA,
IERC20 _rewardTokenB,
bool _hasNativeReward
) public {
chef = _chef;
rewardTokenA = _rewardTokenA;
rewardTokenB = _rewardTokenB;
hasNativeReward = _hasNativeReward;
}
event LPDeposited(uint256 pid, address pair, uint256 amount);
modifier validSavingsRate(uint256 _savingsRate) {
require(
_savingsRate >= 0 && _savingsRate <= 1000,
"You have selected a savings rate outside of the range (0-100%)."
);
_;
}
/** @dev This function allows the user to create a new LP position as
* long as the contract holds enough tokens given the desired amounts
* and slippage allowance.
*/
function createNewLPAndDeposit(CreateLPData calldata _data)
external
onlyOwner
{
_createNewLPAndDeposit(_data);
}
/** @dev This function allows the user to compound an existing LP
* position by harvesting any pending rewards with the MiniChef
* contract, swapping the rewards for the underlying LP assets,
* swapping these assets for the LP token and then depositing into
* the LP.
*/
function autoCompoundExistingLPPosition(
uint256 _pid,
address _pair,
RewardsForTokensPaths[] calldata _data
) external onlyOwner {
uint256 preClaimRewardsBalance = address(this).balance;
_claimRewards(_pid);
// _data will always be length = 2.
for (uint256 i = 0; i < _data.length; i++) {
uint256[] memory amounts = _swapRewardsForLPAssets(
_data[i],
preClaimRewardsBalance
);
}
address tokenA = _data[0].tokenAPath[_data[0].tokenAPath.length - 1];
address tokenB = _data[0].tokenBPath[_data[0].tokenBPath.length - 1];
(address token0, address token1) = UniswapV2Library.sortTokens(
tokenA,
tokenB
);
(uint112 reserve0, uint112 reserve1, ) = IUniswapV2Pair(_pair)
.getReserves();
uint256 amount0 = IERC20(token0).balanceOf(address(this));
uint256 amount1 = router.quote(amount0, reserve0, reserve1);
uint256 token1Balance = IERC20(token1).balanceOf(address(this));
if (amount1 > token1Balance) {
amount0 = router.quote(token1Balance, reserve1, reserve0);
amount1 = router.quote(amount0, reserve0, reserve1);
}
CreateLPData memory data;
data.pid = _pid;
data.pair = _pair;
data.tokenA = token0;
data.tokenB = token1;
data.amountADesired = amount0;
data.amountBDesired = amount1;
_createNewLPAndDeposit(data);
}
function claimRewards(uint256 _pid) external override onlyOwner {
_claimRewards(_pid);
}
function removeLP(
address _tokenA,
address _tokenB,
uint256 _liquidity,
uint256 _amountAMin,
uint256 _amountBMin
) external override onlyOwner {
address pair = UniswapV2Library.pairFor(
router.factory(),
_tokenA,
_tokenB
);
IERC20(pair).approve(address(router), _liquidity);
(uint256 amountA, uint256 amountB) = router.removeLiquidity(
_tokenA,
_tokenB,
_liquidity,
_amountAMin,
_amountBMin,
address(this),
block.timestamp
);
}
function removeLPETH(
address _token,
uint256 _liquidity,
uint256 _amountTokensMin,
uint256 _amountETHMin
) external override onlyOwner {
address pair = UniswapV2Library.pairFor(
router.factory(),
_token,
router.WETH()
);
IERC20(pair).approve(address(router), _liquidity);
(uint256 amountToken, uint256 amountETH) = router.removeLiquidityETH(
_token,
_liquidity,
_amountTokensMin,
_amountETHMin,
address(this),
block.timestamp
);
}
function lpBalance(address _pair)
external
override
returns (uint256 _balance)
{
return IUniswapV2Pair(_pair).balanceOf(address(this));
}
function setOwner(address _newOwner) external override onlyOwner {
transferOwnership(_newOwner);
}
function withdrawETH() external payable override onlyOwner {
(bool success, ) = msg.sender.call{value: address(this).balance}("");
require(success, "SushiFarmer: ETH Withdrawal failed.");
}
function withdrawFunds(address _asset, uint256 _amount)
external
override
onlyOwner
{
bool success = IERC20(_asset).transfer(msg.sender, _amount);
require(success, "SushiFarmer: Withdrawal failed.");
}
function withdrawLP(uint256 _pid, uint256 _amount)
public
override
onlyOwner
{
chef.withdraw(_pid, _amount, address(this));
}
function getLPTokensETH(
address _token,
uint256 _amountTokensDesired,
uint256 _amountETHMin,
uint256 _slippage
) public payable override onlyOwner returns (uint256) {
return
_getLPTokensETH(
_token,
_amountTokensDesired,
_amountETHMin,
_slippage
);
}
/** @dev Allow the user to set reward savings rate. That is, they can
* choose how much of the rewards they'd like to save specifically
* for each token, this value dicates how much of the rewards will be
* used to autocompound their existing LP position.
*/
function setRewardSavings(uint256 _rewardARate, uint256 _rewardBRate)
public
onlyOwner
validSavingsRate(_rewardARate)
validSavingsRate(_rewardBRate)
{
rewardASavingsRate = _rewardARate;
rewardBSavingsRate = _rewardBRate;
}
function setRewardTokens(address _rewardTokenA, address _rewardTokenB)
public
onlyOwner
{
rewardTokenA = IERC20(_rewardTokenA);
rewardTokenB = IERC20(_rewardTokenB);
}
function _getLPTokensETH(
address _token,
uint256 _amountTokensDesired,
uint256 _amountETHMin,
uint256 _slippage
) internal returns (uint256) {
IERC20(_token).approve(address(router), _amountTokensDesired);
uint256 amountTokenMin = _getMinAmount(_amountTokensDesired, _slippage);
(uint256 amountToken, uint256 amountWETH, uint256 liquidity) = router
.addLiquidityETH(
_token,
_amountTokensDesired,
amountTokenMin,
_amountETHMin,
address(this),
block.timestamp
);
return liquidity;
}
/** @dev Really only to be used for testing. */
function getLPTokens(
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 _amountBDesired
) external onlyOwner returns (uint256) {
return _getLPTokens(_tokenA, _tokenB, _amountADesired, _amountBDesired);
}
function _getLPTokens(
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 _amountBDesired
) internal override returns (uint256) {
IERC20(_tokenA).approve(address(router), _amountADesired);
IERC20(_tokenB).approve(address(router), _amountBDesired);
(uint256 amountA, uint256 amountB, uint256 liquidity) = router
.addLiquidity(
_tokenA,
_tokenB,
_amountADesired,
_amountBDesired,
_amountADesired,
_amountBDesired,
address(this),
block.timestamp
);
return liquidity;
}
function _createNewLPAndDeposit(CreateLPData memory _data) internal {
CreateLPData memory data = _data;
uint256 liquidity = _getLPTokens(
data.tokenA,
data.tokenB,
data.amountADesired,
data.amountBDesired
);
_depositLP(data.pair, data.pid, liquidity);
emit LPDeposited(data.pid, data.pair, liquidity);
}
function _depositLP(
address _lpToken,
uint256 _pid,
uint256 _amount
) internal override {
IERC20(_lpToken).approve(address(chef), _amount);
chef.deposit(_pid, _amount, address(this));
}
function _claimRewards(uint256 _pid) internal {
chef.harvest(_pid, address(this));
}
function _swapRewardsForLPAssets(
RewardsForTokensPaths calldata _data,
uint256 _preClaimRewardsBalance
) public payable override onlyOwner returns (uint256[] memory) {
if (hasNativeReward) {
// we want to retain pre reward balance for executing txn's
uint256 amount = address(this).balance - _preClaimRewardsBalance;
IWrappedToken(address(rewardTokenB)).deposit{value: amount}();
}
RewardsForTokensPaths calldata data = _data;
address rewardToken = data.tokenAPath[0];
uint256 rewardBalance = IERC20(rewardToken).balanceOf(address(this));
uint256 allotedRewardBalance = rewardToken == address(rewardTokenA)
? rewardBalance
.mul(ONE_HUNDRED_PERCENT.sub(rewardASavingsRate))
.div(ONE_HUNDRED_PERCENT)
: rewardBalance
.mul(ONE_HUNDRED_PERCENT.sub(rewardBSavingsRate))
.div(ONE_HUNDRED_PERCENT);
// approve reward token spend by the router for this txn
IERC20(rewardToken).approve(address(router), allotedRewardBalance);
uint256 splitRewardsBalance = allotedRewardBalance.div(2);
// swap reward tokens for token A
// however, if for example, we receive Sushi as a reward and Sushi is
// also one of the underlying assets, there is no need to swap this reward
if (data.tokenAPath[0] != data.tokenAPath[data.tokenAPath.length - 1]) {
uint256[] memory amounts0 = _swapExactRewardsForTokens(
splitRewardsBalance,
data.tokenAPath
);
}
// swap reward tokens for token B
if (data.tokenBPath[0] != data.tokenBPath[data.tokenBPath.length - 1]) {
uint256[] memory amounts1 = _swapExactRewardsForTokens(
splitRewardsBalance,
data.tokenBPath
);
}
}
receive() external payable {}
function _swapExactRewardsForTokens(
uint256 _splitRewardsBalance,
address[] calldata _path
) internal returns (uint256[] memory) {
uint256[] memory amountsOut = router.getAmountsOut(
_splitRewardsBalance,
_path
);
uint256[] memory amounts = router.swapExactTokensForTokens(
_splitRewardsBalance,
amountsOut[amountsOut.length - 1],
_path,
address(this),
block.timestamp
);
return amounts;
}
}
| * @dev This function allows the user to create a new LP position as long as the contract holds enough tokens given the desired amounts and slippage allowance./ | function createNewLPAndDeposit(CreateLPData calldata _data)
external
onlyOwner
{
_createNewLPAndDeposit(_data);
}
| 12,624,807 | [
1,
2503,
445,
5360,
326,
729,
358,
752,
279,
394,
511,
52,
1754,
487,
1525,
487,
326,
6835,
14798,
7304,
2430,
864,
326,
6049,
30980,
471,
272,
3169,
2433,
1699,
1359,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
15291,
14461,
1876,
758,
1724,
12,
1684,
14461,
751,
745,
892,
389,
892,
13,
203,
202,
202,
9375,
203,
202,
202,
3700,
5541,
203,
202,
95,
203,
202,
202,
67,
2640,
1908,
14461,
1876,
758,
1724,
24899,
892,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.16;
/**
* @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;
}
}
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
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();
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 is Pausable{
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
uint256 totalSupplyForDivision;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal whenNotPaused{
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public whenNotPaused {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public whenNotPaused
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) whenNotPaused
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public whenPaused returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
totalSupplyForDivision = totalSupply; // Update totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public whenPaused returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
totalSupplyForDivision = totalSupply; // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
/******************************************/
/* ADVANCED TOKEN STARTS HERE */
/******************************************/
contract DunkPayToken is TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
uint256 public buySupply;
uint256 public totalEth;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
function DunkPayToken() TokenERC20(totalSupply, name, symbol) public {
buyPrice = 1000;
sellPrice = 1000;
name = "DunkPay Token";
symbol = "DNK";
totalSupply = buyPrice * 10000 * 10 ** uint256(decimals);
balanceOf[msg.sender] = buyPrice * 5100 * 10 ** uint256(decimals);
balanceOf[this] = totalSupply - balanceOf[msg.sender];
buySupply = balanceOf[this];
allowance[this][msg.sender] = buySupply;
totalSupplyForDivision = totalSupply;// Set the symbol for display purposes
totalEth = address(this).balance;
}
function percent(uint256 numerator, uint256 denominator , uint precision) returns(uint256 quotient) {
if(numerator <= 0)
{
return 0;
}
// caution, check safe-to-multiply here
uint256 _numerator = numerator * 10 ** uint256(precision+1);
// with rounding of last digit
uint256 _quotient = ((_numerator / denominator) - 5) / 10;
return _quotient;
}
function getZero(uint256 number) returns(uint num_len) {
uint i = 1;
uint _num_len = 0;
while( number > i )
{
i *= 10;
_num_len++;
}
return _num_len;
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
buySupply = balanceOf[this]; //For Additonal Supply.
allowance[this][msg.sender] = buySupply;
emit Transfer(_from, _to, _value);
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
buySupply = balanceOf[this]; //For Additonal Supply.
allowance[this][msg.sender] = buySupply;
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice, uint256 newBuySupply) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
buySupply = newBuySupply;
}
function transfer(address _to, uint256 _value) public whenNotPaused {
if(_to == address(this)){
sell(_value);
}else{
_transfer(msg.sender, _to, _value);
}
}
function () payable public {
buy();
}
/// @notice Buy tokens from contract by sending ether
function buy() payable whenNotPaused public {
uint256 dnkForBuy = msg.value;
uint zeros = getZero(buySupply);
uint256 interest = msg.value / 2 * percent(balanceOf[this] , buySupply , zeros);
interest = interest / 10 ** uint256(zeros);
dnkForBuy = dnkForBuy + interest;
_transfer(this, msg.sender, dnkForBuy * buyPrice); // makes the transfers
totalEth += msg.value;
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) whenNotPaused public {
uint256 ethForSell = amount;
uint zeros = getZero(balanceOf[this]);
uint256 interest = amount / 2 * percent( buySupply , balanceOf[this] ,zeros);
interest = interest / 10 ** uint256(zeros);
ethForSell = ethForSell - interest;
ethForSell = ethForSell - (ethForSell/100); // minus 1% for refund fee.
ethForSell = ethForSell / sellPrice;
uint256 minimumAmount = address(this).balance;
require(minimumAmount >= ethForSell); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(ethForSell); // sends ether to the seller. It's important to do this last to avoid recursion attacks
totalEth -= ethForSell;
}
/// @notice withDraw `amount` ETH to contract
/// @param amount amount of ETH to be sent
function withdraw(uint256 amount) onlyOwner public {
uint256 minimumAmount = address(this).balance;
require(minimumAmount >= amount); // checks if the contract has enough ether to buy
msg.sender.transfer(amount); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
function airdrop(address[] _holders, uint256 mintedAmount) onlyOwner whenPaused public {
for (uint i = 0; i < _holders.length; i++) {
uint zeros = getZero(totalSupplyForDivision);
uint256 amount = percent(balanceOf[_holders[i]],totalSupplyForDivision,zeros) * mintedAmount;
amount = amount / 10 ** uint256(zeros);
if(amount != 0){
mintToken(_holders[i], amount);
}
}
totalSupplyForDivision = totalSupply;
}
function bankrupt(address[] _holders) onlyOwner whenPaused public {
uint256 restBalance = balanceOf[this];
totalSupplyForDivision = totalSupply - restBalance; // Update totalSupply
totalEth = address(this).balance;
for (uint i = 0; i < _holders.length; i++) {
uint zeros = getZero(totalSupplyForDivision);
uint256 amount = percent(balanceOf[_holders[i]],totalSupplyForDivision , zeros) * totalEth;
amount = amount / 10 ** uint256(zeros);
if(amount != 0){
uint256 minimumAmount = address(this).balance;
require(minimumAmount >= amount); // checks if the contract has enough ether to buy
uint256 holderBalance = balanceOf[_holders[i]];
balanceOf[_holders[i]] -= holderBalance; // Subtract from the targeted balance
totalSupply -= holderBalance;
_holders[i].transfer(amount); // sends ether to the seller. It's important to do this last to
}
}
totalSupplyForDivision = totalSupply;
totalEth = address(this).balance;
}
} | @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth @param newSellPrice Price the users can sell to the contract @param newBuyPrice Price users can buy from the contract | function setPrices(uint256 newSellPrice, uint256 newBuyPrice, uint256 newBuySupply) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
buySupply = newBuySupply;
}
| 13,883,470 | [
1,
7009,
3677,
358,
30143,
2430,
364,
1375,
2704,
38,
9835,
5147,
68,
13750,
471,
357,
80,
2430,
364,
1375,
2704,
55,
1165,
5147,
68,
13750,
225,
30826,
1165,
5147,
20137,
326,
3677,
848,
357,
80,
358,
326,
6835,
225,
394,
38,
9835,
5147,
20137,
3677,
848,
30143,
628,
326,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
31862,
12,
11890,
5034,
30826,
1165,
5147,
16,
2254,
5034,
394,
38,
9835,
5147,
16,
2254,
5034,
394,
38,
9835,
3088,
1283,
13,
1338,
5541,
1071,
288,
203,
3639,
357,
80,
5147,
273,
30826,
1165,
5147,
31,
203,
3639,
30143,
5147,
273,
394,
38,
9835,
5147,
31,
203,
3639,
30143,
3088,
1283,
273,
394,
38,
9835,
3088,
1283,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/4/0xF849226f5B1829C6Fb583BDfC84b1A65968744BA/sources/CandyMasterFarmer.sol | Safe candy transfer function, just in case if rounding error causes pool to not have enough CNDYs. | function safeCandyTransfer(address _to, uint256 _amount) internal {
uint256 candyBal = candy.balanceOf(address(this));
if (_amount > candyBal) {
candy.transfer(_to, candyBal);
candy.transfer(_to, _amount);
}
}
| 8,565,408 | [
1,
9890,
15350,
93,
7412,
445,
16,
2537,
316,
648,
309,
13885,
555,
14119,
2845,
358,
486,
1240,
7304,
385,
2908,
61,
87,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4183,
39,
464,
93,
5912,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
2713,
288,
203,
3639,
2254,
5034,
15350,
93,
38,
287,
273,
15350,
93,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
67,
8949,
405,
15350,
93,
38,
287,
13,
288,
203,
5411,
15350,
93,
18,
13866,
24899,
869,
16,
15350,
93,
38,
287,
1769,
203,
5411,
15350,
93,
18,
13866,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "IERC20.sol";
import "SafeMath.sol";
import "Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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;
}
}
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol
// Added public isInitialized() view of private initialized bool.
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
/**
* @dev Return true if and only if the contract has been initialized
* @return whether the contract has been initialized
*/
function isInitialized() public view returns (bool) {
return initialized;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {Address} from "Address.sol";
import {Context} from "Context.sol";
import {IERC20} from "IERC20.sol";
import {SafeMath} from "SafeMath.sol";
import {Initializable} from "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 ERC20 is Initializable, 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.
*/
function __ERC20_initialize(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 virtual view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public virtual override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function updateNameAndSymbol(string memory __name, string memory __symbol) internal {
_name = __name;
_symbol = __symbol;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {Context} from "Context.sol";
import {Initializable} from "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.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {IERC20} from "IERC20.sol";
interface IYToken is IERC20 {
function getPricePerFullShare() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {IERC20} from "IERC20.sol";
import {IYToken} from "IYToken.sol";
interface ICurve {
function calc_token_amount(uint256[4] memory amounts, bool deposit) external view returns (uint256);
function get_virtual_price() external view returns (uint256);
}
interface ICurveGauge {
function balanceOf(address depositor) external view returns (uint256);
function minter() external returns (ICurveMinter);
function deposit(uint256 amount) external;
function withdraw(uint256 amount) external;
}
interface ICurveMinter {
function mint(address gauge) external;
function token() external view returns (IERC20);
}
interface ICurvePool {
function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount,
bool donate_dust
) external;
function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);
function token() external view returns (IERC20);
function curve() external view returns (ICurve);
function coins(int128 id) external view returns (IYToken);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {IERC20} from "IERC20.sol";
/**
* TruePool is an ERC20 which represents a share of a pool
*
* This contract can be used to wrap opportunities to be compatible
* with TrueFi and allow users to directly opt-in through the TUSD contract
*
* Each TruePool is also a staking opportunity for TRU
*/
interface ITrueFiPool is IERC20 {
/// @dev pool token (TUSD)
function currencyToken() external view returns (IERC20);
/**
* @dev join pool
* 1. Transfer TUSD from sender
* 2. Mint pool tokens based on value to sender
*/
function join(uint256 amount) external;
/**
* @dev borrow from pool
* 1. Transfer TUSD to sender
* 2. Only lending pool should be allowed to call this
*/
function borrow(uint256 amount, uint256 fee) external;
/**
* @dev join pool
* 1. Transfer TUSD from sender
* 2. Only lending pool should be allowed to call this
*/
function repay(uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
interface ITrueLender {
function value() external view returns (uint256);
function distribute(
address recipient,
uint256 numerator,
uint256 denominator
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
interface IUniswapRouter {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity 0.6.10;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt(uint256 x) internal pure returns (int128) {
require(x <= 0x7FFFFFFFFFFFFFFF);
return int128(x << 64);
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2(int128 x) internal pure returns (int128) {
require(x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) {
xc >>= 64;
msb += 64;
}
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = (msb - 64) << 64;
uint256 ux = uint256(x) << uint256(127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256(b);
}
return int128(result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln(int128 x) internal pure returns (int128) {
require(x > 0);
return int128((uint256(log_2(x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
interface ICrvPriceOracle {
function usdToCrv(uint256 amount) external view returns (uint256);
function crvToUsd(uint256 amount) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
/**
* @dev interface to allow standard pause function
*/
interface IPauseableContract {
function setPauseStatus(bool pauseStatus) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {IERC20} from "IERC20.sol";
import {ERC20} from "UpgradeableERC20.sol";
import {ITrueFiPool2} from "ITrueFiPool2.sol";
interface ILoanToken2 is IERC20 {
enum Status {Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated}
function borrower() external view returns (address);
function amount() external view returns (uint256);
function term() external view returns (uint256);
function apy() external view returns (uint256);
function start() external view returns (uint256);
function lender() external view returns (address);
function debt() external view returns (uint256);
function pool() external view returns (ITrueFiPool2);
function profit() external view returns (uint256);
function status() external view returns (Status);
function getParameters()
external
view
returns (
uint256,
uint256,
uint256
);
function fund() external;
function withdraw(address _beneficiary) external;
function settle() external;
function enterDefault() external;
function liquidate() external;
function redeem(uint256 _amount) external;
function repay(address _sender, uint256 _amount) external;
function repayInFull(address _sender) external;
function reclaim() external;
function allowTransfer(address account, bool _status) external;
function repaid() external view returns (uint256);
function isRepaid() external view returns (bool);
function balance() external view returns (uint256);
function value(uint256 _balance) external view returns (uint256);
function token() external view returns (ERC20);
function version() external pure returns (uint8);
}
//interface IContractWithPool {
// function pool() external view returns (ITrueFiPool2);
//}
//
//// Had to be split because of multiple inheritance problem
//interface ILoanToken2 is ILoanToken, IContractWithPool {
//
//}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {ITrueFiPool2} from "ITrueFiPool2.sol";
import {ILoanToken2} from "ILoanToken2.sol";
interface ITrueLender2 {
// @dev calculate overall value of the pools
function value(ITrueFiPool2 pool) external view returns (uint256);
// @dev distribute a basket of tokens for exiting user
function distribute(
address recipient,
uint256 numerator,
uint256 denominator
) external;
function transferAllLoanTokens(ILoanToken2 loan, address recipient) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {IERC20} from "IERC20.sol";
interface IERC20WithDecimals is IERC20 {
function decimals() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {IERC20WithDecimals} from "IERC20WithDecimals.sol";
/**
* @dev Oracle that converts any token to and from TRU
* Used for liquidations and valuing of liquidated TRU in the pool
*/
interface ITrueFiPoolOracle {
// token address
function token() external view returns (IERC20WithDecimals);
// amount of tokens 1 TRU is worth
function truToToken(uint256 truAmount) external view returns (uint256);
// amount of TRU 1 token is worth
function tokenToTru(uint256 tokenAmount) external view returns (uint256);
// USD price of token with 18 decimals
function tokenToUsd(uint256 tokenAmount) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
interface I1Inch3 {
struct SwapDescription {
address srcToken;
address dstToken;
address srcReceiver;
address dstReceiver;
uint256 amount;
uint256 minReturnAmount;
uint256 flags;
bytes permit;
}
function swap(
address caller,
SwapDescription calldata desc,
bytes calldata data
)
external
returns (
uint256 returnAmount,
uint256 gasLeft,
uint256 chiSpent
);
function unoswap(
address srcToken,
uint256 amount,
uint256 minReturn,
bytes32[] calldata /* pools */
) external payable returns (uint256 returnAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {IERC20} from "IERC20.sol";
import {ILoanToken2} from "ILoanToken2.sol";
interface IDeficiencyToken is IERC20 {
function loan() external view returns (ILoanToken2);
function burnFrom(address account, uint256 amount) external;
function version() external pure returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {IDeficiencyToken} from "IDeficiencyToken.sol";
import {ILoanToken2} from "ILoanToken2.sol";
interface ISAFU {
function poolDeficit(address pool) external view returns (uint256);
function deficiencyToken(ILoanToken2 loan) external view returns (IDeficiencyToken);
function reclaim(ILoanToken2 loan, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {ERC20, IERC20} from "UpgradeableERC20.sol";
import {ITrueLender2, ILoanToken2} from "ITrueLender2.sol";
import {ITrueFiPoolOracle} from "ITrueFiPoolOracle.sol";
import {I1Inch3} from "I1Inch3.sol";
import {ISAFU} from "ISAFU.sol";
interface ITrueFiPool2 is IERC20 {
function initialize(
ERC20 _token,
ITrueLender2 _lender,
ISAFU safu,
address __owner
) external;
function singleBorrowerInitialize(
ERC20 _token,
ITrueLender2 _lender,
ISAFU safu,
address __owner,
string memory borrowerName,
string memory borrowerSymbol
) external;
function token() external view returns (ERC20);
function oracle() external view returns (ITrueFiPoolOracle);
function poolValue() external view returns (uint256);
/**
* @dev Ratio of liquid assets in the pool to the pool value
*/
function liquidRatio() external view returns (uint256);
/**
* @dev Ratio of liquid assets in the pool after lending
* @param amount Amount of asset being lent
*/
function proFormaLiquidRatio(uint256 amount) external view returns (uint256);
/**
* @dev Join the pool by depositing tokens
* @param amount amount of tokens to deposit
*/
function join(uint256 amount) external;
/**
* @dev borrow from pool
* 1. Transfer TUSD to sender
* 2. Only lending pool should be allowed to call this
*/
function borrow(uint256 amount) external;
/**
* @dev pay borrowed money back to pool
* 1. Transfer TUSD from sender
* 2. Only lending pool should be allowed to call this
*/
function repay(uint256 currencyAmount) external;
/**
* @dev SAFU buys LoanTokens from the pool
*/
function liquidate(ILoanToken2 loan) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {ILoanToken2} from "ILoanToken2.sol";
import {ITrueLender2} from "ITrueLender2.sol";
import {ISAFU} from "ISAFU.sol";
/**
* @dev Library that has shared functions between legacy TrueFi Pool and Pool2
*/
library PoolExtensions {
function _liquidate(
ISAFU safu,
ILoanToken2 loan,
ITrueLender2 lender
) internal {
require(msg.sender == address(safu), "TrueFiPool: Should be called by SAFU");
lender.transferAllLoanTokens(loan, address(safu));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {IERC20} from "IERC20.sol";
import {ReentrancyGuard} from "ReentrancyGuard.sol";
import {SafeMath} from "SafeMath.sol";
import {SafeERC20} from "SafeERC20.sol";
import {ERC20} from "UpgradeableERC20.sol";
import {Ownable} from "UpgradeableOwnable.sol";
import {ICurveGauge, ICurveMinter, ICurvePool} from "ICurve.sol";
import {ITrueFiPool} from "ITrueFiPool.sol";
import {ITrueLender} from "ITrueLender.sol";
import {IUniswapRouter} from "IUniswapRouter.sol";
import {ABDKMath64x64} from "Log.sol";
import {ICrvPriceOracle} from "ICrvPriceOracle.sol";
import {IPauseableContract} from "IPauseableContract.sol";
import {ITrueFiPool2, ITrueFiPoolOracle, ITrueLender2, ILoanToken2, ISAFU} from "ITrueFiPool2.sol";
import {PoolExtensions} from "PoolExtensions.sol";
/**
* @title TrueFi Pool
* @dev Lending pool which uses curve.fi to store idle funds
* Earn high interest rates on currency deposits through uncollateralized loans
*
* Funds deposited in this pool are not fully liquid. Liquidity
* Exiting incurs an exit penalty depending on pool liquidity
* After exiting, an account will need to wait for LoanTokens to expire and burn them
* It is recommended to perform a zap or swap tokens on Uniswap for increased liquidity
*
* Funds are managed through an external function to save gas on deposits
*/
contract TrueFiPool is ITrueFiPool, IPauseableContract, ERC20, ReentrancyGuard, Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// ================ WARNING ==================
// ===== THIS CONTRACT IS INITIALIZABLE ======
// === STORAGE VARIABLES ARE DECLARED BELOW ==
// REMOVAL OR REORDER OF VARIABLES WILL RESULT
// ========= IN STORAGE CORRUPTION ===========
ICurvePool public _curvePool;
ICurveGauge public _curveGauge;
IERC20 public token;
ITrueLender public _lender;
ICurveMinter public _minter;
IUniswapRouter public _uniRouter;
// fee for deposits
uint256 public joiningFee;
// track claimable fees
uint256 public claimableFees;
mapping(address => uint256) latestJoinBlock;
address private DEPRECATED__stakeToken;
// cache values during sync for gas optimization
bool private inSync;
uint256 private yTokenValueCache;
uint256 private loansValueCache;
// TRU price oracle
ITrueFiPoolOracle public oracle;
// fund manager can call functions to help manage pool funds
// fund manager can be set to 0 or governance
address public fundsManager;
// allow pausing of deposits
bool public pauseStatus;
// CRV price oracle
ICrvPriceOracle public _crvOracle;
ITrueLender2 public _lender2;
ISAFU public safu;
// ======= STORAGE DECLARATION END ============
// curve.fi data
uint8 constant N_TOKENS = 4;
uint8 constant TUSD_INDEX = 3;
uint256 constant MAX_PRICE_SLIPPAGE = 10; // 0.1%
/**
* @dev Emitted when TrueFi oracle was changed
* @param newOracle New oracle address
*/
event TruOracleChanged(ITrueFiPoolOracle newOracle);
/**
* @dev Emitted when CRV oracle was changed
* @param newOracle New oracle address
*/
event CrvOracleChanged(ICrvPriceOracle newOracle);
/**
* @dev Emitted when funds manager is changed
* @param newManager New manager address
*/
event FundsManagerChanged(address newManager);
/**
* @dev Emitted when fee is changed
* @param newFee New fee
*/
event JoiningFeeChanged(uint256 newFee);
/**
* @dev Emitted when someone joins the pool
* @param staker Account staking
* @param deposited Amount deposited
* @param minted Amount of pool tokens minted
*/
event Joined(address indexed staker, uint256 deposited, uint256 minted);
/**
* @dev Emitted when someone exits the pool
* @param staker Account exiting
* @param amount Amount unstaking
*/
event Exited(address indexed staker, uint256 amount);
/**
* @dev Emitted when funds are flushed into curve.fi
* @param currencyAmount Amount of tokens deposited
*/
event Flushed(uint256 currencyAmount);
/**
* @dev Emitted when funds are pulled from curve.fi
* @param yAmount Amount of pool tokens
*/
event Pulled(uint256 yAmount);
/**
* @dev Emitted when funds are borrowed from pool
* @param borrower Borrower address
* @param amount Amount of funds borrowed from pool
* @param fee Fees collected from this transaction
*/
event Borrow(address borrower, uint256 amount, uint256 fee);
/**
* @dev Emitted when borrower repays the pool
* @param payer Address of borrower
* @param amount Amount repaid
*/
event Repaid(address indexed payer, uint256 amount);
/**
* @dev Emitted when fees are collected
* @param beneficiary Account to receive fees
* @param amount Amount of fees collected
*/
event Collected(address indexed beneficiary, uint256 amount);
/**
* @dev Emitted when joining is paused or unpaused
* @param pauseStatus New pausing status
*/
event PauseStatusChanged(bool pauseStatus);
/**
* @dev Emitted when SAFU address is changed
* @param newSafu New SAFU address
*/
event SafuChanged(ISAFU newSafu);
/**
* @dev only lender can perform borrowing or repaying
*/
modifier onlyLender() {
require(msg.sender == address(_lender) || msg.sender == address(_lender2), "TrueFiPool: Caller is not the lender");
_;
}
/**
* @dev pool can only be joined when it's unpaused
*/
modifier joiningNotPaused() {
require(!pauseStatus, "TrueFiPool: Joining the pool is paused");
_;
}
/**
* @dev only lender can perform borrowing or repaying
*/
modifier onlyOwnerOrManager() {
require(msg.sender == owner() || msg.sender == fundsManager, "TrueFiPool: Caller is neither owner nor funds manager");
_;
}
/**
* @dev ensure than as a result of running a function,
* balance of `token` increases by at least `expectedGain`
*/
modifier exchangeProtector(uint256 expectedGain, IERC20 _token) {
uint256 balanceBefore = _token.balanceOf(address(this));
_;
uint256 balanceDiff = _token.balanceOf(address(this)).sub(balanceBefore);
require(balanceDiff >= conservativePriceEstimation(expectedGain), "TrueFiPool: Not optimal exchange");
}
/**
* Sync values to avoid making expensive calls multiple times
* Will set inSync to true, allowing getter functions to return cached values
* Wipes cached values to save gas
*/
modifier sync() {
// sync
yTokenValueCache = yTokenValue();
loansValueCache = loansValue();
inSync = true;
_;
// wipe
inSync = false;
yTokenValueCache = 0;
loansValueCache = 0;
}
function updateNameAndSymbolToLegacy() public {
updateNameAndSymbol("Legacy TrueFi TrueUSD", "Legacy tfTUSD");
}
/// @dev support borrow function from pool V2
function borrow(uint256 amount) external {
borrow(amount, 0);
}
/**
* @dev get currency token address
* @return currency token address
*/
function currencyToken() public override view returns (IERC20) {
return token;
}
/**
* @dev set TrueLenderV2
*/
function setLender2(ITrueLender2 lender2) public onlyOwner {
require(address(_lender2) == address(0), "TrueFiPool: Lender 2 is already set");
_lender2 = lender2;
}
/**
* @dev set funds manager address
*/
function setFundsManager(address newFundsManager) public onlyOwner {
fundsManager = newFundsManager;
emit FundsManagerChanged(newFundsManager);
}
/**
* @dev set TrueFi price oracle token address
* @param newOracle new oracle address
*/
function setTruOracle(ITrueFiPoolOracle newOracle) public onlyOwner {
oracle = newOracle;
emit TruOracleChanged(newOracle);
}
/**
* @dev set CRV price oracle token address
* @param newOracle new oracle address
*/
function setCrvOracle(ICrvPriceOracle newOracle) public onlyOwner {
_crvOracle = newOracle;
emit CrvOracleChanged(newOracle);
}
/**
* @dev Allow pausing of deposits in case of emergency
* @param status New deposit status
*/
function setPauseStatus(bool status) external override onlyOwnerOrManager {
pauseStatus = status;
emit PauseStatusChanged(status);
}
/**
* @dev Change SAFU address
*/
function setSafuAddress(ISAFU _safu) external onlyOwner {
safu = _safu;
emit SafuChanged(_safu);
}
/**
* @dev Get total balance of CRV tokens
* @return Balance of stake tokens in this contract
*/
function crvBalance() public view returns (uint256) {
if (address(_minter) == address(0)) {
return 0;
}
return _minter.token().balanceOf(address(this));
}
/**
* @dev Get total balance of curve.fi pool tokens
* @return Balance of y pool tokens in this contract
*/
function yTokenBalance() public view returns (uint256) {
return _curvePool.token().balanceOf(address(this)).add(_curveGauge.balanceOf(address(this)));
}
/**
* @dev Virtual value of yCRV tokens in the pool
* Will return sync value if inSync
* @return yTokenValue in USD.
*/
function yTokenValue() public view returns (uint256) {
if (inSync) {
return yTokenValueCache;
}
return yTokenBalance().mul(_curvePool.curve().get_virtual_price()).div(1 ether);
}
/**
* @dev Price of CRV in USD
* @return Oracle price of TRU in USD
*/
function crvValue() public view returns (uint256) {
uint256 balance = crvBalance();
if (balance == 0 || address(_crvOracle) == address(0)) {
return 0;
}
return conservativePriceEstimation(_crvOracle.crvToUsd(balance));
}
/**
* @dev Virtual value of liquid assets in the pool
* @return Virtual liquid value of pool assets
*/
function liquidValue() public view returns (uint256) {
return currencyBalance().add(yTokenValue());
}
/**
* @dev Return pool deficiency value, to be returned by safu
* @return pool deficiency value
*/
function deficitValue() public view returns (uint256) {
if (address(safu) == address(0)) {
return 0;
}
return safu.poolDeficit(address(this));
}
/**
* @dev Calculate pool value in TUSD
* "virtual price" of entire pool - LoanTokens, TUSD, curve y pool tokens
* @return pool value in USD
*/
function poolValue() public view returns (uint256) {
// this assumes defaulted loans are worth their full value
return liquidValue().add(loansValue()).add(crvValue()).add(deficitValue());
}
/**
* @dev Virtual value of loan assets in the pool
* Will return cached value if inSync
* @return Value of loans in pool
*/
function loansValue() public view returns (uint256) {
if (inSync) {
return loansValueCache;
}
if (address(_lender2) != address(0)) {
return _lender.value().add(_lender2.value(ITrueFiPool2(address(this))));
}
return _lender.value();
}
/**
* @dev ensure enough curve.fi pool tokens are available
* Check if current available amount of TUSD is enough and
* withdraw remainder from gauge
* @param neededAmount amount required
*/
function ensureEnoughTokensAreAvailable(uint256 neededAmount) internal {
uint256 currentlyAvailableAmount = _curvePool.token().balanceOf(address(this));
if (currentlyAvailableAmount < neededAmount) {
_curveGauge.withdraw(neededAmount.sub(currentlyAvailableAmount));
}
}
/**
* @dev set pool join fee
* @param fee new fee
*/
function setJoiningFee(uint256 fee) external onlyOwner {
require(fee <= 10000, "TrueFiPool: Fee cannot exceed transaction value");
joiningFee = fee;
emit JoiningFeeChanged(fee);
}
/**
* @dev Join the pool by depositing currency tokens
* @param amount amount of currency token to deposit
*/
function join(uint256 amount) external override joiningNotPaused {
uint256 fee = amount.mul(joiningFee).div(10000);
uint256 mintedAmount = mint(amount.sub(fee));
claimableFees = claimableFees.add(fee);
latestJoinBlock[tx.origin] = block.number;
require(token.transferFrom(msg.sender, address(this), amount));
emit Joined(msg.sender, amount, mintedAmount);
}
/**
* @dev Exit pool only with liquid tokens
* This function will withdraw TUSD but with a small penalty
* Uses the sync() modifier to reduce gas costs of using curve
* @param amount amount of pool tokens to redeem for underlying tokens
*/
function liquidExit(uint256 amount) external nonReentrant sync {
require(block.number != latestJoinBlock[tx.origin], "TrueFiPool: Cannot join and exit in same block");
require(amount <= balanceOf(msg.sender), "TrueFiPool: Insufficient funds");
uint256 amountToWithdraw = poolValue().mul(amount).div(totalSupply());
require(amountToWithdraw <= liquidValue(), "TrueFiPool: Not enough liquidity in pool");
// burn tokens sent
_burn(msg.sender, amount);
if (amountToWithdraw > currencyBalance()) {
removeLiquidityFromCurve(amountToWithdraw.sub(currencyBalance()));
require(amountToWithdraw <= currencyBalance(), "TrueFiPool: Not enough funds were withdrawn from Curve");
}
require(token.transfer(msg.sender, amountToWithdraw));
emit Exited(msg.sender, amountToWithdraw);
}
/**
* @dev Deposit idle funds into curve.fi pool and stake in gauge
* Called by owner to help manage funds in pool and save on gas for deposits
* @param currencyAmount Amount of funds to deposit into curve
*/
function flush(uint256 currencyAmount) external {
require(currencyAmount <= currencyBalance(), "TrueFiPool: Insufficient currency balance");
uint256 expectedMinYTokenValue = yTokenValue().add(conservativePriceEstimation(currencyAmount));
_curvePoolDeposit(currencyAmount);
require(yTokenValue() >= expectedMinYTokenValue, "TrueFiPool: yToken value expected to be higher");
emit Flushed(currencyAmount);
}
function _curvePoolDeposit(uint256 currencyAmount) private {
uint256[N_TOKENS] memory amounts = [0, 0, 0, currencyAmount];
token.safeApprove(address(_curvePool), currencyAmount);
uint256 conservativeMinAmount = calcTokenAmount(currencyAmount).mul(999).div(1000);
_curvePool.add_liquidity(amounts, conservativeMinAmount);
// stake yCurve tokens in gauge
uint256 yBalance = _curvePool.token().balanceOf(address(this));
_curvePool.token().safeApprove(address(_curveGauge), yBalance);
_curveGauge.deposit(yBalance);
}
/**
* @dev Remove liquidity from curve
* @param yAmount amount of curve pool tokens
* @param minCurrencyAmount minimum amount of tokens to withdraw
*/
function pull(uint256 yAmount, uint256 minCurrencyAmount) external onlyOwnerOrManager {
require(yAmount <= yTokenBalance(), "TrueFiPool: Insufficient Curve liquidity balance");
// unstake in gauge
ensureEnoughTokensAreAvailable(yAmount);
// remove TUSD from curve
_curvePool.token().safeApprove(address(_curvePool), yAmount);
_curvePool.remove_liquidity_one_coin(yAmount, TUSD_INDEX, minCurrencyAmount, false);
emit Pulled(yAmount);
}
// prettier-ignore
/**
* @dev Remove liquidity from curve if necessary and transfer to lender
* @param amount amount for lender to withdraw
*/
function borrow(uint256 amount, uint256 fee) public override nonReentrant onlyLender {
// if there is not enough TUSD, withdraw from curve
if (amount > currencyBalance()) {
removeLiquidityFromCurve(amount.sub(currencyBalance()));
require(amount <= currencyBalance(), "TrueFiPool: Not enough funds in pool to cover borrow");
}
mint(fee);
require(token.transfer(msg.sender, amount.sub(fee)));
emit Borrow(msg.sender, amount, fee);
}
function removeLiquidityFromCurve(uint256 amountToWithdraw) internal {
// get rough estimate of how much yCRV we should sell
uint256 roughCurveTokenAmount = calcTokenAmount(amountToWithdraw).mul(1005).div(1000);
require(roughCurveTokenAmount <= yTokenBalance(), "TrueFiPool: Not enough Curve liquidity tokens in pool to cover borrow");
// pull tokens from gauge
ensureEnoughTokensAreAvailable(roughCurveTokenAmount);
// remove TUSD from curve
_curvePool.token().safeApprove(address(_curvePool), roughCurveTokenAmount);
uint256 minAmount = roughCurveTokenAmount.mul(_curvePool.curve().get_virtual_price()).mul(999).div(1000).div(1 ether);
_curvePool.remove_liquidity_one_coin(roughCurveTokenAmount, TUSD_INDEX, minAmount, false);
}
/**
* @dev repay debt by transferring tokens to the contract
* @param currencyAmount amount to repay
*/
function repay(uint256 currencyAmount) external override onlyLender {
require(token.transferFrom(msg.sender, address(this), currencyAmount));
emit Repaid(msg.sender, currencyAmount);
}
/**
* @dev Collect CRV tokens minted by staking at gauge
*/
function collectCrv() external onlyOwnerOrManager {
_minter.mint(address(_curveGauge));
}
/**
* @dev Sell collected CRV on Uniswap
* - Selling CRV is managed by the contract owner
* - Calculations can be made off-chain and called based on market conditions
* - Need to pass path of exact pairs to go through while executing exchange
* For example, CRV -> WETH -> TUSD
*
* @param amountIn see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens
* @param amountOutMin see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens
* @param path see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens
*/
function sellCrv(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path
) public exchangeProtector(_crvOracle.crvToUsd(amountIn), token) {
_minter.token().safeApprove(address(_uniRouter), amountIn);
_uniRouter.swapExactTokensForTokens(amountIn, amountOutMin, path, address(this), block.timestamp + 1 hours);
}
/**
* @dev Claim fees from the pool
* @param beneficiary account to send funds to
*/
function collectFees(address beneficiary) external onlyOwnerOrManager {
uint256 amount = claimableFees;
claimableFees = 0;
if (amount > 0) {
require(token.transfer(beneficiary, amount));
}
emit Collected(beneficiary, amount);
}
/**
* @dev Function called by SAFU when liquidation happens. It will transfer all tokens of this loan the SAFU
*/
function liquidate(ILoanToken2 loan) external {
PoolExtensions._liquidate(safu, loan, _lender2);
}
/**
* @notice Expected amount of minted Curve.fi yDAI/yUSDC/yUSDT/yTUSD tokens.
* Can be used to control slippage
* Called in flush() function
* @param currencyAmount amount to calculate for
* @return expected amount minted given currency amount
*/
function calcTokenAmount(uint256 currencyAmount) public view returns (uint256) {
// prettier-ignore
uint256 yTokenAmount = currencyAmount.mul(1e18).div(
_curvePool.coins(TUSD_INDEX).getPricePerFullShare());
uint256[N_TOKENS] memory yAmounts = [0, 0, 0, yTokenAmount];
return _curvePool.curve().calc_token_amount(yAmounts, true);
}
/**
* @dev Currency token balance
* @return Currency token balance
*/
function currencyBalance() public view returns (uint256) {
return token.balanceOf(address(this)).sub(claimableFees);
}
/**
* @param depositedAmount Amount of currency deposited
* @return amount minted from this transaction
*/
function mint(uint256 depositedAmount) internal returns (uint256) {
uint256 mintedAmount = depositedAmount;
if (mintedAmount == 0) {
return mintedAmount;
}
// first staker mints same amount deposited
if (totalSupply() > 0) {
mintedAmount = totalSupply().mul(depositedAmount).div(poolValue());
}
// mint pool tokens
_mint(msg.sender, mintedAmount);
return mintedAmount;
}
/**
* @dev Calculate price minus max percentage of slippage during exchange
* This will lead to the pool value become a bit undervalued
* compared to the oracle price but will ensure that the value doesn't drop
* when token exchanges are performed.
*/
function conservativePriceEstimation(uint256 price) internal pure returns (uint256) {
return price.mul(uint256(10000).sub(MAX_PRICE_SLIPPAGE)).div(10000);
}
}
| * @title TrueFi Pool @dev Lending pool which uses curve.fi to store idle funds Earn high interest rates on currency deposits through uncollateralized loans Funds deposited in this pool are not fully liquid. Liquidity Exiting incurs an exit penalty depending on pool liquidity After exiting, an account will need to wait for LoanTokens to expire and burn them It is recommended to perform a zap or swap tokens on Uniswap for increased liquidity Funds are managed through an external function to save gas on deposits/ ================ WARNING ================== ===== THIS CONTRACT IS INITIALIZABLE ====== === STORAGE VARIABLES ARE DECLARED BELOW == REMOVAL OR REORDER OF VARIABLES WILL RESULT ========= IN STORAGE CORRUPTION =========== fee for deposits track claimable fees cache values during sync for gas optimization TRU price oracle fund manager can call functions to help manage pool funds fund manager can be set to 0 or governance allow pausing of deposits CRV price oracle ======= STORAGE DECLARATION END ============ curve.fi data | contract TrueFiPool is ITrueFiPool, IPauseableContract, ERC20, ReentrancyGuard, Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
ICurvePool public _curvePool;
ICurveGauge public _curveGauge;
IERC20 public token;
ITrueLender public _lender;
ICurveMinter public _minter;
IUniswapRouter public _uniRouter;
uint256 public joiningFee;
uint256 public claimableFees;
mapping(address => uint256) latestJoinBlock;
address private DEPRECATED__stakeToken;
bool private inSync;
uint256 private yTokenValueCache;
uint256 private loansValueCache;
ITrueFiPoolOracle public oracle;
address public fundsManager;
bool public pauseStatus;
ICrvPriceOracle public _crvOracle;
ITrueLender2 public _lender2;
ISAFU public safu;
uint8 constant N_TOKENS = 4;
uint8 constant TUSD_INDEX = 3;
event TruOracleChanged(ITrueFiPoolOracle newOracle);
event CrvOracleChanged(ICrvPriceOracle newOracle);
event FundsManagerChanged(address newManager);
event JoiningFeeChanged(uint256 newFee);
event Joined(address indexed staker, uint256 deposited, uint256 minted);
event Exited(address indexed staker, uint256 amount);
event Flushed(uint256 currencyAmount);
event Pulled(uint256 yAmount);
event Borrow(address borrower, uint256 amount, uint256 fee);
event Repaid(address indexed payer, uint256 amount);
event Collected(address indexed beneficiary, uint256 amount);
event PauseStatusChanged(bool pauseStatus);
event SafuChanged(ISAFU newSafu);
pragma solidity 0.6.10;
import {IERC20} from "IERC20.sol";
import {ReentrancyGuard} from "ReentrancyGuard.sol";
import {SafeMath} from "SafeMath.sol";
import {SafeERC20} from "SafeERC20.sol";
import {ERC20} from "UpgradeableERC20.sol";
import {Ownable} from "UpgradeableOwnable.sol";
import {ICurveGauge, ICurveMinter, ICurvePool} from "ICurve.sol";
import {ITrueFiPool} from "ITrueFiPool.sol";
import {ITrueLender} from "ITrueLender.sol";
import {IUniswapRouter} from "IUniswapRouter.sol";
import {ABDKMath64x64} from "Log.sol";
import {ICrvPriceOracle} from "ICrvPriceOracle.sol";
import {IPauseableContract} from "IPauseableContract.sol";
import {ITrueFiPool2, ITrueFiPoolOracle, ITrueLender2, ILoanToken2, ISAFU} from "ITrueFiPool2.sol";
import {PoolExtensions} from "PoolExtensions.sol";
modifier onlyLender() {
require(msg.sender == address(_lender) || msg.sender == address(_lender2), "TrueFiPool: Caller is not the lender");
_;
}
modifier joiningNotPaused() {
require(!pauseStatus, "TrueFiPool: Joining the pool is paused");
_;
}
modifier onlyOwnerOrManager() {
require(msg.sender == owner() || msg.sender == fundsManager, "TrueFiPool: Caller is neither owner nor funds manager");
_;
}
modifier exchangeProtector(uint256 expectedGain, IERC20 _token) {
uint256 balanceBefore = _token.balanceOf(address(this));
_;
uint256 balanceDiff = _token.balanceOf(address(this)).sub(balanceBefore);
require(balanceDiff >= conservativePriceEstimation(expectedGain), "TrueFiPool: Not optimal exchange");
}
modifier sync() {
yTokenValueCache = yTokenValue();
loansValueCache = loansValue();
inSync = true;
_;
inSync = false;
yTokenValueCache = 0;
loansValueCache = 0;
}
function updateNameAndSymbolToLegacy() public {
updateNameAndSymbol("Legacy TrueFi TrueUSD", "Legacy tfTUSD");
}
function borrow(uint256 amount) external {
borrow(amount, 0);
}
function currencyToken() public override view returns (IERC20) {
return token;
}
function setLender2(ITrueLender2 lender2) public onlyOwner {
require(address(_lender2) == address(0), "TrueFiPool: Lender 2 is already set");
_lender2 = lender2;
}
function setFundsManager(address newFundsManager) public onlyOwner {
fundsManager = newFundsManager;
emit FundsManagerChanged(newFundsManager);
}
function setTruOracle(ITrueFiPoolOracle newOracle) public onlyOwner {
oracle = newOracle;
emit TruOracleChanged(newOracle);
}
function setCrvOracle(ICrvPriceOracle newOracle) public onlyOwner {
_crvOracle = newOracle;
emit CrvOracleChanged(newOracle);
}
function setPauseStatus(bool status) external override onlyOwnerOrManager {
pauseStatus = status;
emit PauseStatusChanged(status);
}
function setSafuAddress(ISAFU _safu) external onlyOwner {
safu = _safu;
emit SafuChanged(_safu);
}
function crvBalance() public view returns (uint256) {
if (address(_minter) == address(0)) {
return 0;
}
return _minter.token().balanceOf(address(this));
}
function crvBalance() public view returns (uint256) {
if (address(_minter) == address(0)) {
return 0;
}
return _minter.token().balanceOf(address(this));
}
function yTokenBalance() public view returns (uint256) {
return _curvePool.token().balanceOf(address(this)).add(_curveGauge.balanceOf(address(this)));
}
function yTokenValue() public view returns (uint256) {
if (inSync) {
return yTokenValueCache;
}
return yTokenBalance().mul(_curvePool.curve().get_virtual_price()).div(1 ether);
}
function yTokenValue() public view returns (uint256) {
if (inSync) {
return yTokenValueCache;
}
return yTokenBalance().mul(_curvePool.curve().get_virtual_price()).div(1 ether);
}
function crvValue() public view returns (uint256) {
uint256 balance = crvBalance();
if (balance == 0 || address(_crvOracle) == address(0)) {
return 0;
}
return conservativePriceEstimation(_crvOracle.crvToUsd(balance));
}
function crvValue() public view returns (uint256) {
uint256 balance = crvBalance();
if (balance == 0 || address(_crvOracle) == address(0)) {
return 0;
}
return conservativePriceEstimation(_crvOracle.crvToUsd(balance));
}
function liquidValue() public view returns (uint256) {
return currencyBalance().add(yTokenValue());
}
function deficitValue() public view returns (uint256) {
if (address(safu) == address(0)) {
return 0;
}
return safu.poolDeficit(address(this));
}
function deficitValue() public view returns (uint256) {
if (address(safu) == address(0)) {
return 0;
}
return safu.poolDeficit(address(this));
}
function poolValue() public view returns (uint256) {
return liquidValue().add(loansValue()).add(crvValue()).add(deficitValue());
}
function loansValue() public view returns (uint256) {
if (inSync) {
return loansValueCache;
}
if (address(_lender2) != address(0)) {
return _lender.value().add(_lender2.value(ITrueFiPool2(address(this))));
}
return _lender.value();
}
function loansValue() public view returns (uint256) {
if (inSync) {
return loansValueCache;
}
if (address(_lender2) != address(0)) {
return _lender.value().add(_lender2.value(ITrueFiPool2(address(this))));
}
return _lender.value();
}
function loansValue() public view returns (uint256) {
if (inSync) {
return loansValueCache;
}
if (address(_lender2) != address(0)) {
return _lender.value().add(_lender2.value(ITrueFiPool2(address(this))));
}
return _lender.value();
}
function ensureEnoughTokensAreAvailable(uint256 neededAmount) internal {
uint256 currentlyAvailableAmount = _curvePool.token().balanceOf(address(this));
if (currentlyAvailableAmount < neededAmount) {
_curveGauge.withdraw(neededAmount.sub(currentlyAvailableAmount));
}
}
function ensureEnoughTokensAreAvailable(uint256 neededAmount) internal {
uint256 currentlyAvailableAmount = _curvePool.token().balanceOf(address(this));
if (currentlyAvailableAmount < neededAmount) {
_curveGauge.withdraw(neededAmount.sub(currentlyAvailableAmount));
}
}
function setJoiningFee(uint256 fee) external onlyOwner {
require(fee <= 10000, "TrueFiPool: Fee cannot exceed transaction value");
joiningFee = fee;
emit JoiningFeeChanged(fee);
}
function join(uint256 amount) external override joiningNotPaused {
uint256 fee = amount.mul(joiningFee).div(10000);
uint256 mintedAmount = mint(amount.sub(fee));
claimableFees = claimableFees.add(fee);
latestJoinBlock[tx.origin] = block.number;
require(token.transferFrom(msg.sender, address(this), amount));
emit Joined(msg.sender, amount, mintedAmount);
}
function liquidExit(uint256 amount) external nonReentrant sync {
require(block.number != latestJoinBlock[tx.origin], "TrueFiPool: Cannot join and exit in same block");
require(amount <= balanceOf(msg.sender), "TrueFiPool: Insufficient funds");
uint256 amountToWithdraw = poolValue().mul(amount).div(totalSupply());
require(amountToWithdraw <= liquidValue(), "TrueFiPool: Not enough liquidity in pool");
_burn(msg.sender, amount);
if (amountToWithdraw > currencyBalance()) {
removeLiquidityFromCurve(amountToWithdraw.sub(currencyBalance()));
require(amountToWithdraw <= currencyBalance(), "TrueFiPool: Not enough funds were withdrawn from Curve");
}
require(token.transfer(msg.sender, amountToWithdraw));
emit Exited(msg.sender, amountToWithdraw);
}
function liquidExit(uint256 amount) external nonReentrant sync {
require(block.number != latestJoinBlock[tx.origin], "TrueFiPool: Cannot join and exit in same block");
require(amount <= balanceOf(msg.sender), "TrueFiPool: Insufficient funds");
uint256 amountToWithdraw = poolValue().mul(amount).div(totalSupply());
require(amountToWithdraw <= liquidValue(), "TrueFiPool: Not enough liquidity in pool");
_burn(msg.sender, amount);
if (amountToWithdraw > currencyBalance()) {
removeLiquidityFromCurve(amountToWithdraw.sub(currencyBalance()));
require(amountToWithdraw <= currencyBalance(), "TrueFiPool: Not enough funds were withdrawn from Curve");
}
require(token.transfer(msg.sender, amountToWithdraw));
emit Exited(msg.sender, amountToWithdraw);
}
function flush(uint256 currencyAmount) external {
require(currencyAmount <= currencyBalance(), "TrueFiPool: Insufficient currency balance");
uint256 expectedMinYTokenValue = yTokenValue().add(conservativePriceEstimation(currencyAmount));
_curvePoolDeposit(currencyAmount);
require(yTokenValue() >= expectedMinYTokenValue, "TrueFiPool: yToken value expected to be higher");
emit Flushed(currencyAmount);
}
function _curvePoolDeposit(uint256 currencyAmount) private {
uint256[N_TOKENS] memory amounts = [0, 0, 0, currencyAmount];
token.safeApprove(address(_curvePool), currencyAmount);
uint256 conservativeMinAmount = calcTokenAmount(currencyAmount).mul(999).div(1000);
_curvePool.add_liquidity(amounts, conservativeMinAmount);
uint256 yBalance = _curvePool.token().balanceOf(address(this));
_curvePool.token().safeApprove(address(_curveGauge), yBalance);
_curveGauge.deposit(yBalance);
}
function pull(uint256 yAmount, uint256 minCurrencyAmount) external onlyOwnerOrManager {
require(yAmount <= yTokenBalance(), "TrueFiPool: Insufficient Curve liquidity balance");
ensureEnoughTokensAreAvailable(yAmount);
_curvePool.token().safeApprove(address(_curvePool), yAmount);
_curvePool.remove_liquidity_one_coin(yAmount, TUSD_INDEX, minCurrencyAmount, false);
emit Pulled(yAmount);
}
function borrow(uint256 amount, uint256 fee) public override nonReentrant onlyLender {
if (amount > currencyBalance()) {
removeLiquidityFromCurve(amount.sub(currencyBalance()));
require(amount <= currencyBalance(), "TrueFiPool: Not enough funds in pool to cover borrow");
}
mint(fee);
require(token.transfer(msg.sender, amount.sub(fee)));
emit Borrow(msg.sender, amount, fee);
}
function borrow(uint256 amount, uint256 fee) public override nonReentrant onlyLender {
if (amount > currencyBalance()) {
removeLiquidityFromCurve(amount.sub(currencyBalance()));
require(amount <= currencyBalance(), "TrueFiPool: Not enough funds in pool to cover borrow");
}
mint(fee);
require(token.transfer(msg.sender, amount.sub(fee)));
emit Borrow(msg.sender, amount, fee);
}
function removeLiquidityFromCurve(uint256 amountToWithdraw) internal {
uint256 roughCurveTokenAmount = calcTokenAmount(amountToWithdraw).mul(1005).div(1000);
require(roughCurveTokenAmount <= yTokenBalance(), "TrueFiPool: Not enough Curve liquidity tokens in pool to cover borrow");
ensureEnoughTokensAreAvailable(roughCurveTokenAmount);
_curvePool.token().safeApprove(address(_curvePool), roughCurveTokenAmount);
uint256 minAmount = roughCurveTokenAmount.mul(_curvePool.curve().get_virtual_price()).mul(999).div(1000).div(1 ether);
_curvePool.remove_liquidity_one_coin(roughCurveTokenAmount, TUSD_INDEX, minAmount, false);
}
function repay(uint256 currencyAmount) external override onlyLender {
require(token.transferFrom(msg.sender, address(this), currencyAmount));
emit Repaid(msg.sender, currencyAmount);
}
function collectCrv() external onlyOwnerOrManager {
_minter.mint(address(_curveGauge));
}
function sellCrv(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path
) public exchangeProtector(_crvOracle.crvToUsd(amountIn), token) {
_minter.token().safeApprove(address(_uniRouter), amountIn);
_uniRouter.swapExactTokensForTokens(amountIn, amountOutMin, path, address(this), block.timestamp + 1 hours);
}
function collectFees(address beneficiary) external onlyOwnerOrManager {
uint256 amount = claimableFees;
claimableFees = 0;
if (amount > 0) {
require(token.transfer(beneficiary, amount));
}
emit Collected(beneficiary, amount);
}
function collectFees(address beneficiary) external onlyOwnerOrManager {
uint256 amount = claimableFees;
claimableFees = 0;
if (amount > 0) {
require(token.transfer(beneficiary, amount));
}
emit Collected(beneficiary, amount);
}
function liquidate(ILoanToken2 loan) external {
PoolExtensions._liquidate(safu, loan, _lender2);
}
function calcTokenAmount(uint256 currencyAmount) public view returns (uint256) {
uint256 yTokenAmount = currencyAmount.mul(1e18).div(
_curvePool.coins(TUSD_INDEX).getPricePerFullShare());
uint256[N_TOKENS] memory yAmounts = [0, 0, 0, yTokenAmount];
return _curvePool.curve().calc_token_amount(yAmounts, true);
}
function currencyBalance() public view returns (uint256) {
return token.balanceOf(address(this)).sub(claimableFees);
}
function mint(uint256 depositedAmount) internal returns (uint256) {
uint256 mintedAmount = depositedAmount;
if (mintedAmount == 0) {
return mintedAmount;
}
if (totalSupply() > 0) {
mintedAmount = totalSupply().mul(depositedAmount).div(poolValue());
}
return mintedAmount;
}
function mint(uint256 depositedAmount) internal returns (uint256) {
uint256 mintedAmount = depositedAmount;
if (mintedAmount == 0) {
return mintedAmount;
}
if (totalSupply() > 0) {
mintedAmount = totalSupply().mul(depositedAmount).div(poolValue());
}
return mintedAmount;
}
function mint(uint256 depositedAmount) internal returns (uint256) {
uint256 mintedAmount = depositedAmount;
if (mintedAmount == 0) {
return mintedAmount;
}
if (totalSupply() > 0) {
mintedAmount = totalSupply().mul(depositedAmount).div(poolValue());
}
return mintedAmount;
}
_mint(msg.sender, mintedAmount);
function conservativePriceEstimation(uint256 price) internal pure returns (uint256) {
return price.mul(uint256(10000).sub(MAX_PRICE_SLIPPAGE)).div(10000);
}
}
| 12,253,096 | [
1,
5510,
42,
77,
8828,
225,
511,
2846,
2845,
1492,
4692,
8882,
18,
22056,
358,
1707,
12088,
284,
19156,
512,
1303,
3551,
16513,
17544,
603,
5462,
443,
917,
1282,
3059,
6301,
22382,
2045,
287,
1235,
437,
634,
478,
19156,
443,
1724,
329,
316,
333,
2845,
854,
486,
7418,
4501,
26595,
18,
511,
18988,
24237,
9500,
310,
316,
2789,
392,
2427,
23862,
8353,
603,
2845,
4501,
372,
24237,
7360,
15702,
16,
392,
2236,
903,
1608,
358,
2529,
364,
3176,
304,
5157,
358,
6930,
471,
18305,
2182,
2597,
353,
14553,
358,
3073,
279,
11419,
578,
7720,
2430,
603,
1351,
291,
91,
438,
364,
31383,
4501,
372,
24237,
478,
19156,
854,
7016,
3059,
392,
3903,
445,
358,
1923,
16189,
603,
443,
917,
1282,
19,
422,
26678,
9744,
28562,
422,
12275,
20676,
8020,
2849,
1268,
4437,
12584,
15154,
2782,
422,
894,
757,
2347,
15553,
22965,
55,
432,
862,
2030,
15961,
5879,
9722,
4130,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
1053,
42,
77,
2864,
353,
467,
5510,
42,
77,
2864,
16,
2971,
1579,
429,
8924,
16,
4232,
39,
3462,
16,
868,
8230,
12514,
16709,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
203,
565,
467,
9423,
2864,
1071,
389,
16683,
2864,
31,
203,
565,
467,
9423,
18941,
1071,
389,
16683,
18941,
31,
203,
565,
467,
654,
39,
3462,
1071,
1147,
31,
203,
565,
467,
5510,
48,
2345,
1071,
389,
80,
2345,
31,
203,
565,
467,
9423,
49,
2761,
1071,
389,
1154,
387,
31,
203,
565,
467,
984,
291,
91,
438,
8259,
1071,
389,
318,
77,
8259,
31,
203,
203,
565,
2254,
5034,
1071,
21239,
14667,
31,
203,
565,
2254,
5034,
1071,
7516,
429,
2954,
281,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
4891,
4572,
1768,
31,
203,
203,
565,
1758,
3238,
2030,
14838,
972,
334,
911,
1345,
31,
203,
203,
565,
1426,
3238,
316,
4047,
31,
203,
565,
2254,
5034,
3238,
677,
1345,
620,
1649,
31,
203,
565,
2254,
5034,
3238,
437,
634,
620,
1649,
31,
203,
203,
565,
467,
5510,
42,
77,
2864,
23601,
1071,
20865,
31,
203,
203,
565,
1758,
1071,
284,
19156,
1318,
31,
203,
203,
565,
1426,
1071,
11722,
1482,
31,
203,
203,
565,
26899,
4962,
5147,
23601,
1071,
389,
3353,
90,
23601,
31,
203,
203,
565,
467,
5510,
48,
2345,
22,
1071,
389,
80,
2345,
22,
31,
203,
203,
565,
4437,
6799,
57,
1071,
2
] |
pragma solidity ^0.5.8;
import "./ERC721.sol";
import "./IERC721Entity.sol";
/**
* @title Contract ERC721Entity is ERC721, and implements IERC721Entity
* @author Brian Ludlam
*
* ERC721Entity Contract defines a standard ERC721 token, and then extends the
* functionality to give entity-type properties and functionality. An entity is
* defined here as a unique non-fungible token having: owner-mutable name, immutable
* age, immutable traceable lineage, and immutable genes propagated with both randomness
* and rarity. Entity creation requires two transactions total: First createEntity is
* called by the intended owner, which places the entity into a spawning pool with a
* pre-determined spawn block. After that, someone calling spawnEntity on or after the entity's
* spawn block, will spawn that entity, giving it genes. Genes are applied using the
* randomness of the pre-determined spawn block's hash combined with it's blind
* semi-random spawner.
*
* Entity Creation
*
* Creating an entity starts with calling createEntity, with a name and optional
* parents. If no parents are given, the entity will be spawned with random rarity
* genes. If parents given, the entity will be spawned with random combinatorial genes.
* Each successful call to createEntity will cost 4 finney, which is payed in-full
* indirectly to the future spawner of the created entity.
*
* Entity Genes
*
* Entity Genes are specified as 32 8bit (0-255) values, which can be used as
* a property such as hair color, or as the entity's "potential"
* in some activity, for example: max movement speed or strength. The applied
* genes must have both randomness and rarity. Randomness is achieved in this
* implementation by either: Random Rarity Propagation, when created without
* parents, or Random Combinatorial Propagation, when created with parents.
* Both use a pre-determined future block hash, combined with blind
* semi-random spawning, to achieve randomness.
*
* Random Rarity Propagation
*
* With Random Rarity Propagation an entity is spawned, without parents,
* randomly giving it an exponentially curved set of possible gene values.
* Roughly half of all gene values spawned will be between 32 and 64,
* with each value above that being increasingly more rare. Maximum rarity for a
* single gene is 1:256, representing max gene value of 255. Getting all 32 genes
* at 255, has odds of 1:256^32, a 77 digit number, relatively impossible.
*
* Random Combinatorial Propagation
*
* With Random Combinatorial Propagation an entity has parents, and therefore
* spawned with random gene values - between the values' of each of it's parents'
* genes. The min gene resulting value, will always be the lower of the two parent
* genes, and the higher of the two parent genes being the max, of any specific
* gene being randomized in-between those parent gene values.
*
* Entity Lineage
*
* With each entity having either 2 parents or null parents, any entity's origin
* can be traced back to null parent end-nodes, creating a provable tree of lineage.
* An entity can never have only one null parent, either both null/zero, or both
* existing/traceable entities.
*
* Entity Spawning
*
* Once created using createEntity, an entity goes into a spawning pool with
* a pre-determined spawn block and zeroed/null genes. On or after that
* pre-determined spawn block, spawnEntity can be called to spwan the entity,
* providing it with genes. Transaction spawnEntity can be called by anyone
* at any time, spawning the next queued spawn that is ready. Each successful call
* to spawnEntity pays 4 finney, payed indirectly by a previous caller of
* createEntity. If no spawns in queue, or none that are ready to spawn left on the
* block being called on, transaction will fail at minimal cost (~1/5 finney.)
* If 5 spawnEntity transactions occur on the same block, and only 4 spawns are
* ready on that block, the fifth call will fail.
*
* Entity Renaming
*
* Entity owner can rename entity at any time by calling nameEntity, for
* example, renaming an entity after purchasing it from someone else. Entity
* name will always be chopped at a 32 byte max.
*
* Entity Expiration
*
* Given the Ethereum block-history-limit of 256 blocks, if a spawning entity
* reaches 255 blocks from pre-determined spawn block without being spawned, that
* entity's spawning becomes expired. An expired entity, cannot be spawned and
* therefore has permanently zeroed genes. Spawning is blind to the spawner, and
* queued in order, so for an entity to become expired, a full-stop in spawning
* must occur for 255 blocks, which should be relatively rare. If an entity creator
* is the only spawning force currently in play, it is their responsibility to spawn
* entities they have created. Claiming spawning reward, plays a more major role in
* motivating spawning activity of course. A call to spawnEntity, with expired spawn
* next in queue, still pays the spawner as always, but will result in a cheaper
* transaction, so expired spawns are never a penalty to spawner (to avoid backlog
* of expired spawns of any kind.) The number of entities ready to spawn, can be
* determined on any block, by calling spawnCount.
*
* Note on Block Hash Randomness
*
* Obviously pseudo-random, and miner generated, but relatively random enough for
* it's given purpose. Miners have some control over block hash creation, but the
* process involves GPUs trying millions of nonces per second each translating into
* a different block hash. Once a nonce result hits the target difficulty, the new
* block immediately propagates in attempt to win the block creation reward. Any
* additional "rerolling" of nonce attempts and/or reordering transactions to find
* a more desirable resulting hash value exponentially adds risk of losing the block
* creation reward. Therefore, all block hash random values used must not translate
* into potential value over block reward, currently 3+ Eth, to ensure it's never
* worth it for miners to take that risk. Even if they do, it amounts to a series
* of re-rolls, and never direct control over exact block hash value.
*
* Miners also control transaction ordering, which can effect outcome to some degree,
* but not enough to cause any significant advantage or adverse disadvantage. Future
* block hash value (as opposed to current block hash) is used for two reasons: allows
* a built-in 12 block transaction verification process, and prevents any kind of
* read-ahead checking of block hash value by miners on any given block. All block
* hashes used are combined with integral data, so there is no block hash rooted value
* that effects any state values directly. In the case of spawning, in this implementation,
* an exact spawn block - 12 blocks into the future - is set during the createEntity call,
* and then the spawn block's hash is combined with unique entity id and spawner address
* during the spawnEntity call.
*
*/
contract ERC721Entity is ERC721, IERC721Entity {
//number of blocks to cast spawning into future = relatively verified = 12 blocks
uint8 private constant SPAWN_BLOCKS = 12;
//4 finney - transferred from creator to spawner
uint256 private constant SPAWN_FEE = 4000000000000000;
//Parent ids of entity, zeroes if no parents.
struct Parents {//immutable
uint256 a;
uint256 b;
}
//contract developer, power to destroy/upgrade
address payable private _developer;
//Mapping to entity parents. Immutable
mapping (uint256 => Parents) private _parents;
//Mapping to entity spawn block number before spawn, then
//spawn block timestamp after spawn. Immutable
mapping (uint256 => uint256) private _born;
//Mapping to entity genes. Immutable
mapping (uint256 => bytes32) private _genes;
//Mapping to entity name. Mutable by owner
mapping (uint256 => bytes32) private _name;
//internal fifo spawn queue
mapping(uint256 => uint256) private _spawnFarm;
uint256 private _firstSpawn;//spawn queue first index
uint256 private _lastSpawn;//spawn queue last index
constructor() public {
_developer = msg.sender;
_firstSpawn = 1;//init spawn queue
}
/**
* Transaction createEntity - Create token entity with given name and optional parents.
* If parents are null, create new entity with random rarity genes, otherwise create
* entity with random combinatorial genes. Created entity will immediately enter
* spawning poolfor exactly 12 blocks, when it becomes ready for spawning. Use
* spawnEntity to spawn entity. Fee of 4 finney is collected by createEntity,
* and payed out to successful caller of spawnEntity.
* @param name = name of entity, max 32 bytes
* @param parentA = id of parentA entity, or zero
* @param parentA = id of parentB entity, or zero
* @dev name is no more than 32 bytes, string converted to bytes32.
* Parents must be both caller owned entities or both zero.
* TX FEE: 4 finney
* GAS: ~130k-160k (no parents - with parents)
*/
function createEntity(
string calldata name,
uint256 parentA,
uint256 parentB
) external payable {
require (msg.value >= SPAWN_FEE, "Spawn fee not covered.");
require (
(parentA == 0 && parentB == 0) ||
(parentA != parentB &&
ownerOf(parentA) == msg.sender &&
ownerOf(parentB) == msg.sender), "Invalid parents."
);
uint256 id = mintFor(msg.sender);
_parents[id] = Parents(parentA, parentB);
_born[id] = block.number + SPAWN_BLOCKS;//future spawn block
_name[id] = toBytes32(bytes(name));//chop to 32 bytes
_spawnFarm[++_lastSpawn] = id;
if (msg.value > SPAWN_FEE)
msg.sender.transfer(msg.value - SPAWN_FEE);
}
/**
* Transaction spawnEntity - Spawn next ready token entity. Entities are
* spawned blindly in the order they were created; first created, first spawned.
* If no entities ready to spawn on block, transaction will fail. Use
* spawnCount to check current spawn count. Higher the spawn count, relatively
* lesser chance of fail. Successful spawning transaction pays out 4 finney,
* as payed by creator. Fail costs ~1/5 finney. Entity genes are zeroed until spawn.
* Spawn expires, giving it permanent zeroed genes, if not spawned within 255
* blocks of creation.
* TX REWARD: 4 finney
* GAS: ~70k
*/
function spawnEntity() external {
require (
_lastSpawn >= _firstSpawn && //has spawns
block.number >= _born[_spawnFarm[_firstSpawn]],
"No spawns."
);
uint256 id = _spawnFarm[_firstSpawn];
delete _spawnFarm[_firstSpawn++];
//expired spawn if older than 255 blocks = owner penalty = genes remain 0x0
if (block.number <= _born[id] + 255) {
//unique entity id x blind spawner address x predetermined-block hash value
bytes32 nature = keccak256(abi.encodePacked (
id,
msg.sender,
blockhash(_born[id])
));
//If parents are null, spawn with random rarity genes, else random propagate genes
_genes[id] = (
(_parents[id].a == 0 || _parents[id].b == 0) ?
rarityGenes(nature) :
propagateGenes(
_genes[_parents[id].a],
_genes[_parents[id].b],
nature
)
);
}
//switch *born* from birth block number to birth block timestamp
_born[id] = now;
msg.sender.transfer (SPAWN_FEE);
emit Spawned (ownerOf(id), msg.sender, id, now);
}
/**
* Transaction nameEntity - Name the given entity, by id. Owner only.
* @param entity = id of entity
* @param name = name of entity, max 32 bytes
* GAS: ~35k
*/
function nameEntity(uint256 entity, string calldata name) external {
require (ownerOf(entity) == msg.sender);
_name[entity] = toBytes32(bytes(name));//chop to 32 bytes
emit NameChanged (msg.sender, entity, string (abi.encodePacked(_name[entity])), now);
}
/**
* View nameOf Entity
* @param entity = id of entity
* @return name - name of entity as a string.
*/
function nameOf(uint256 entity) external view returns (string memory name) {
name = string (abi.encodePacked(_name[entity]));
}
/**
* View ageOf Entity
* @param entity = id of entity
* @return age = spawn timestamp of entity,
* or zero if not spawned yet.
*/
function ageOf(uint256 entity) external view returns (uint256 age) {
age = ((_genes[entity] == 0x0) ? 0 : now - _born[entity]);
}
/**
* View parentsOf Entity
* @param entity = id of entity
* @return parentA and @return parentB of entity, as two uint
* entity ids. Zeroes if null parents.
*/
function parentsOf(uint256 entity) external view
returns (uint256 parentA, uint256 parentB) {
parentA = _parents[entity].a;
parentB = _parents[entity].b;
}
/**
* View genesOf Entity
* @param entity = id of entity
* @return genes - genes of entity as an array of
* 32 8bit gene values (0-255) each.
*/
function genesOf(uint256 entity) external view returns (uint8[] memory genes) {
genes = decodeGenes(_genes[entity]);
}
/** TODO
* View rarityOf Entity
* @return rarity of entity genes as percent
function rarityOf(uint256 entity) external view returns (uint256 rarity) {
}*/
/**
* View getEntity - returns all entity info
* @param entity = id of entity
* @return owner = entity owner
* @return born = spawn timestamp of entity,
* @return parentA of entity, as uint, zero if none
* @return parentB of entity, as uint, zero if none
* @return name - name of entity as a string.
* @return genes - genes of entity as an array of 32 8 bit values
*/
function getEntity(uint256 entity) external view returns (
address owner,
uint256 born,
uint256 parentA,
uint256 parentB,
string memory name,
uint8[] memory genes
) {
owner = ownerOf(entity);
born = _born[entity];
parentA = _parents[entity].a;
parentB = _parents[entity].b;
name = string (abi.encodePacked(_name[entity]));
genes = decodeGenes(_genes[entity]);
}
/**
* View spawnCount
* @return count - number of spawns ready to spawn
* on current block.
*/
function spawnCount() external view returns (uint256 count) {
count = 0;
while (
_lastSpawn >= (_firstSpawn + count) &&
block.number >= _born[_spawnFarm[_firstSpawn + count]]
) { count++; }
}
/* Testing only - remove from production or add proxy update-able interface */
function destroy() external {
require (_developer == msg.sender);
selfdestruct(_developer);
}
/* Return to sender any abstract transfers */
function () external payable { msg.sender.transfer(msg.value); }
/* INTERNAL PURE */
/**
* @notice internal rarityGenes - get random rarity genes for spawning entity.
* @param nature - randomization source hash
* @return genes for new entity.
*/
function rarityGenes(bytes32 nature) internal pure
returns (bytes32 genes) {
bytes memory geneBytes = new bytes(32);
uint8 rand;
for (uint8 g=0; g<32; g++){
rand = uint8 (nature[g]);
geneBytes[g] = byte (
randomRarityGenes (rand)
);
}
genes = toBytes32(geneBytes);
}
/**
* @notice internal propagateGenes - propagate genes from two given parents.
* @param genesA - genes of parent A. (order is insignificant)
* @param genesB - genes of parent B.
* @param nature - randomization source hash
* @return genes for new entity.
*/
function propagateGenes(bytes32 genesA, bytes32 genesB, bytes32 nature)
internal pure returns (bytes32 genes) {
bytes memory geneBytes = new bytes(32);
uint8 gA;
uint8 gB;
uint8 rand;
for (uint8 g=0; g<32; g++){
gA = uint8 (genesA[g]);
gB = uint8 (genesB[g]);
rand = uint8 (nature[g]);
geneBytes[g] = byte (
(gA == gB) ? gA:
(gA > gB) ? gB + (rand % (1 + gA - gB)) :
gA + (rand % (1 + gB - gA))
);
}
genes = toBytes32(geneBytes);
}
/**
* @notice internal decodeGenes - decode genes from bytes32 to array of 32 uint8s.
* @return genes as array of 32 uint8s.
*/
function decodeGenes(bytes32 genes) internal pure
returns (uint8[] memory geneValues) {
geneValues = new uint8[](32);
for (uint8 g=0; g<32; g++) {
geneValues[g] = uint8 (genes[g]);
}
}
/**
* @notice internal randomRarityGenes - Gene rarity randomizer.
* @param nature - uint8 randomization value
* @return gene of random rarity.
*/
//PROOF OF RARITY
//TODO currently rough numerical sketch of exponential curve
//redo with extact exponential curve translatable to exact rarity prob fig
//32 - 255 (most common - most rare)
//odds of 32-68 ~= 2:1 (50%)
//odds of 255 = 256:1 (0.3%)
//odds of 3x 255 = 256^3:1 = 16,777,216:1 (0.0000006%)
function randomRarityGenes(uint8 nature) internal pure
returns (uint8 gene) {
gene = ((nature % 8) + (8 * (
(nature < 61) ? 4 :
(nature < 102) ? 5 :
(nature < 131) ? 6 :
(nature < 147) ? 7 :
(nature < 157) ? 8 :
(nature < 165) ? 9 :
(nature < 171) ? 10 :
(nature < 177) ? 11 :
(nature < 183) ? 12 :
(nature < 189) ? 13 :
(nature < 195) ? 14 :
(nature < 201) ? 15 :
(nature < 206) ? 16 :
(nature < 211) ? 17 :
(nature < 216) ? 18 :
(nature < 221) ? 19 :
(nature < 226) ? 20 :
(nature < 230) ? 21 :
(nature < 234) ? 22 :
(nature < 238) ? 23 :
(nature < 242) ? 24 :
(nature < 245) ? 25 :
(nature < 248) ? 26 :
(nature < 251) ? 27 :
(nature < 253) ? 28 :
(nature < 254) ? 29 :
(nature < 255) ? 30 : 31
)));
}
/**
* @notice internal toBytes32 - Convert byte array to bytes32
* @param _data - bytes to convert.
* @return data converted bytes32.
*/
function toBytes32(bytes memory _data) internal pure
returns (bytes32 data) {
if (_data.length == 0) return 0x0;
assembly { data := mload(add(_data,32)) }
}
} | Mapping to entity parents. Immutable | mapping (uint256 => Parents) private _parents;
| 7,312,910 | [
1,
3233,
358,
1522,
6298,
18,
7252,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
261,
11890,
5034,
516,
9520,
87,
13,
3238,
389,
12606,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0x6194cD9C04fA346733F0DBA45c4EFe0C00823dCE/sources/KovanLETH.sol | Goals: 1. if the _tokensToRedeem being claimed does not drain the vault to below 160% 2. pull out the amount of ether the senders' tokens entitle them to and send it to them | function redeem(uint _tokensToRedeem)
public
{
(uint collateralToUnlock, uint fee, uint collateralToReturn) = calculateRedemptionValue(_tokensToRedeem);
bytes memory proxyCall = abi.encodeWithSignature(
"freeETH(address,address,uint256,uint256)",
makerManager,
ethGemJoin,
cdpId,
collateralToUnlock);
cdpDSProxy.execute(saverProxyActions, proxyCall);
(bool feePaymentSuccess,) = gulper.call.value(fee)("");
require(feePaymentSuccess, "fee transfer to gulper failed");
_burn(msg.sender, _tokensToRedeem);
(bool payoutSuccess,) = msg.sender.call.value(collateralToReturn)("");
require(payoutSuccess, "eth payment reverted");
emit Redeemed(
msg.sender,
_tokensToRedeem,
fee,
collateralToUnlock,
collateralToReturn);
}
| 8,834,890 | [
1,
5741,
1031,
30,
404,
18,
309,
326,
389,
7860,
774,
426,
24903,
3832,
7516,
329,
1552,
486,
15427,
326,
9229,
358,
5712,
25430,
9,
576,
18,
6892,
596,
326,
3844,
434,
225,
2437,
326,
1366,
414,
11,
2430,
3281,
1280,
2182,
358,
471,
1366,
518,
358,
2182,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
283,
24903,
12,
11890,
389,
7860,
774,
426,
24903,
13,
203,
3639,
1071,
203,
565,
288,
203,
203,
3639,
261,
11890,
4508,
2045,
287,
774,
7087,
16,
2254,
14036,
16,
2254,
4508,
2045,
287,
27014,
13,
273,
4604,
426,
19117,
375,
620,
24899,
7860,
774,
426,
24903,
1769,
203,
203,
3639,
1731,
3778,
2889,
1477,
273,
24126,
18,
3015,
1190,
5374,
12,
203,
5411,
315,
9156,
1584,
44,
12,
2867,
16,
2867,
16,
11890,
5034,
16,
11890,
5034,
2225,
16,
203,
5411,
312,
6388,
1318,
16,
7010,
5411,
13750,
43,
351,
4572,
16,
7010,
5411,
7976,
84,
548,
16,
203,
5411,
4508,
2045,
287,
774,
7087,
1769,
203,
3639,
7976,
84,
3948,
3886,
18,
8837,
12,
13098,
502,
3886,
6100,
16,
2889,
1477,
1769,
203,
203,
3639,
261,
6430,
14036,
6032,
4510,
16,
13,
273,
314,
332,
457,
18,
1991,
18,
1132,
12,
21386,
13,
2932,
8863,
203,
3639,
2583,
12,
21386,
6032,
4510,
16,
315,
21386,
7412,
358,
314,
332,
457,
2535,
8863,
203,
3639,
389,
70,
321,
12,
3576,
18,
15330,
16,
389,
7860,
774,
426,
24903,
1769,
203,
3639,
261,
6430,
293,
2012,
4510,
16,
13,
273,
1234,
18,
15330,
18,
1991,
18,
1132,
12,
12910,
2045,
287,
27014,
13,
2932,
8863,
203,
3639,
2583,
12,
84,
2012,
4510,
16,
315,
546,
5184,
15226,
329,
8863,
203,
203,
3639,
3626,
868,
24903,
329,
12,
203,
5411,
1234,
18,
15330,
16,
7010,
5411,
389,
7860,
774,
426,
24903,
16,
203,
5411,
14036,
16,
203,
5411,
4508,
2045,
287,
774,
7087,
2
] |
./partial_match/56/0x9eeC897F25a8D4b47b587EBc09a1b17260Fb37e4/sources/StrategyAutoCake.sol | * @dev Withdraws funds and sents them back to the vault. It redeposits harvested and pending cakes in AutoFarm strategy via farm() It withdraws {want} from the AutoFarm. The available {want} is returned to the vault./ | function withdraw(uint256 _amount) external {
require(msg.sender == vault, "!vault");
IStratX(autostrat).farm();
IStratX(autostrat).farm();
uint256 wantBal = IERC20(want).balanceOf(address(this));
if (wantBal < _amount) {
IAutoFarmV2(autofarm).withdraw(poolId, _amount.sub(wantBal));
wantBal = IERC20(want).balanceOf(address(this));
}
if (wantBal > _amount) {
wantBal = _amount;
}
IERC20(want).safeTransfer(vault, wantBal);
}
| 11,039,676 | [
1,
1190,
9446,
87,
284,
19156,
471,
3271,
87,
2182,
1473,
358,
326,
9229,
18,
2597,
283,
323,
917,
1282,
17895,
90,
3149,
471,
4634,
276,
3223,
316,
8064,
42,
4610,
6252,
3970,
284,
4610,
1435,
2597,
598,
9446,
87,
288,
17369,
97,
628,
326,
8064,
42,
4610,
18,
1021,
2319,
288,
17369,
97,
353,
2106,
358,
326,
9229,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
12,
11890,
5034,
389,
8949,
13,
3903,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
9229,
16,
17528,
26983,
8863,
203,
203,
3639,
467,
1585,
270,
60,
12,
21996,
313,
270,
2934,
74,
4610,
5621,
203,
3639,
467,
1585,
270,
60,
12,
21996,
313,
270,
2934,
74,
4610,
5621,
203,
203,
3639,
2254,
5034,
2545,
38,
287,
273,
467,
654,
39,
3462,
12,
17369,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
309,
261,
17369,
38,
287,
411,
389,
8949,
13,
288,
203,
5411,
467,
4965,
42,
4610,
58,
22,
12,
5854,
792,
4610,
2934,
1918,
9446,
12,
6011,
548,
16,
389,
8949,
18,
1717,
12,
17369,
38,
287,
10019,
203,
5411,
2545,
38,
287,
273,
467,
654,
39,
3462,
12,
17369,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
289,
203,
203,
3639,
309,
261,
17369,
38,
287,
405,
389,
8949,
13,
288,
203,
5411,
2545,
38,
287,
273,
389,
8949,
31,
203,
3639,
289,
203,
203,
3639,
467,
654,
39,
3462,
12,
17369,
2934,
4626,
5912,
12,
26983,
16,
2545,
38,
287,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0x8cbA3Ef8211B92E086Ea8B131DE8eF152D162e5e/sources/browser/ERC721.sol | * @title ERC721 Non-Fungible Token Standard basic implementation @dev source : openzeppelin-solidity/contracts/token/ERC721/ERC721.sol/ | contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
function balanceOf(address owner) public override view returns (uint256) {
require(owner != address(0), "owner cannot be address 0");
return _ownedTokensCount[owner].current();
}
function ownerOf(uint256 tokenId) public override view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0), "owner cannot be address 0");
return owner;
}
function approve(address to, uint256 tokenId) public override {
address owner = ownerOf(tokenId);
require(to != owner, "cannot approve yourself");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "permission denied");
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
function getApproved(uint256 tokenId) public override view returns (address) {
require(_exists(tokenId), "tokenID doesn't exist");
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address to, bool approved) public override {
require(to != msg.sender, "cannot approve yourself");
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
function isApprovedForAll(address owner, address operator) public override virtual view returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(address from, address to, uint256 tokenId) public override {
require(_isApprovedOrOwner(msg.sender, tokenId), "spender is not approved");
_transferFrom(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId) public override {
safeTransferFromWithData(from, to, tokenId, "");
}
function safeTransferFromWithData(address from, address to, uint256 tokenId, bytes memory _data) public override {
transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "data check is not ok");
}
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "cannot mint to address 0");
require(!_exists(tokenId), "token already exists");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
function _burn(address owner, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == owner, "address is not owner of tokenID");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
function _transferFrom(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "sender is not owner of the token");
require(to != address(0), "cannot send to 0 address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
| 8,236,752 | [
1,
654,
39,
27,
5340,
3858,
17,
42,
20651,
1523,
3155,
8263,
5337,
4471,
225,
1084,
294,
1696,
94,
881,
84,
292,
267,
17,
30205,
560,
19,
16351,
87,
19,
2316,
19,
654,
39,
27,
5340,
19,
654,
39,
27,
5340,
18,
18281,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4232,
39,
27,
5340,
353,
4232,
39,
28275,
16,
467,
654,
39,
27,
5340,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
1071,
3849,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
8443,
480,
1758,
12,
20,
3631,
315,
8443,
2780,
506,
1758,
374,
8863,
203,
3639,
327,
389,
995,
329,
5157,
1380,
63,
8443,
8009,
2972,
5621,
203,
565,
289,
203,
203,
565,
445,
3410,
951,
12,
11890,
5034,
1147,
548,
13,
1071,
3849,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
1758,
3410,
273,
389,
2316,
5541,
63,
2316,
548,
15533,
203,
3639,
2583,
12,
8443,
480,
1758,
12,
20,
3631,
315,
8443,
2780,
506,
1758,
374,
8863,
203,
3639,
327,
3410,
31,
203,
565,
289,
203,
203,
203,
565,
445,
6617,
537,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
1071,
3849,
288,
203,
3639,
1758,
3410,
273,
3410,
951,
12,
2316,
548,
1769,
203,
3639,
2583,
12,
869,
480,
3410,
16,
315,
12892,
6617,
537,
3433,
2890,
8863,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3410,
747,
353,
31639,
1290,
1595,
12,
8443,
16,
1234,
18,
15330,
3631,
315,
9827,
15338,
8863,
203,
203,
3639,
389,
2316,
12053,
4524,
63,
2316,
548,
65,
273,
358,
31,
203,
3639,
3626,
1716,
685,
1125,
12,
8443,
16,
358,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
336,
31639,
12,
11890,
5034,
1147,
548,
13,
2
] |
./partial_match/1/0xBED8a5C8aedCBc5D9c1A2b0b65Da4388A56D8562/sources/IporOracle.sol | @notice Gets point to accounts appointed to rebalance storage. @return store - point to accounts appointed to rebalance storage. | function getAmmPoolsAppointedToRebalanceStorage()
internal
pure
returns (AmmPoolsAppointedToRebalanceStorage storage store)
{
uint256 slot = _getStorageSlot(StorageId.AmmPoolsAppointedToRebalance);
assembly {
store.slot := slot
}
}
| 3,606,928 | [
1,
3002,
1634,
358,
9484,
595,
763,
329,
358,
283,
12296,
2502,
18,
327,
1707,
300,
1634,
358,
9484,
595,
763,
329,
358,
283,
12296,
2502,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4506,
7020,
16639,
1294,
1153,
329,
774,
426,
12296,
3245,
1435,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
37,
7020,
16639,
1294,
1153,
329,
774,
426,
12296,
3245,
2502,
1707,
13,
203,
565,
288,
203,
3639,
2254,
5034,
4694,
273,
389,
588,
3245,
8764,
12,
3245,
548,
18,
37,
7020,
16639,
1294,
1153,
329,
774,
426,
12296,
1769,
203,
3639,
19931,
288,
203,
5411,
1707,
18,
14194,
519,
4694,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: contracts/saga/interfaces/IModelDataSource.sol
pragma solidity 0.4.25;
/**
* @title Model Data Source Interface.
*/
interface IModelDataSource {
/**
* @dev Get interval parameters.
* @param _rowNum Interval row index.
* @param _colNum Interval column index.
* @return Interval minimum amount of SGA.
* @return Interval maximum amount of SGA.
* @return Interval minimum amount of SDR.
* @return Interval maximum amount of SDR.
* @return Interval alpha value (scaled up).
* @return Interval beta value (scaled up).
*/
function getInterval(uint256 _rowNum, uint256 _colNum) external view returns (uint256, uint256, uint256, uint256, uint256, uint256);
/**
* @dev Get interval alpha and beta.
* @param _rowNum Interval row index.
* @param _colNum Interval column index.
* @return Interval alpha value (scaled up).
* @return Interval beta value (scaled up).
*/
function getIntervalCoefs(uint256 _rowNum, uint256 _colNum) external view returns (uint256, uint256);
/**
* @dev Get the amount of SGA required for moving to the next minting-point.
* @param _rowNum Interval row index.
* @return Required amount of SGA.
*/
function getRequiredMintAmount(uint256 _rowNum) external view returns (uint256);
}
// File: contracts/saga/interfaces/IMintingPointTimersManager.sol
pragma solidity 0.4.25;
/**
* @title Minting Point Timers Manager Interface.
*/
interface IMintingPointTimersManager {
/**
* @dev Start a given timestamp.
* @param _id The ID of the timestamp.
* @notice When tested, this timestamp will be either 'running' or 'expired'.
*/
function start(uint256 _id) external;
/**
* @dev Reset a given timestamp.
* @param _id The ID of the timestamp.
* @notice When tested, this timestamp will be neither 'running' nor 'expired'.
*/
function reset(uint256 _id) external;
/**
* @dev Get an indication of whether or not a given timestamp is 'running'.
* @param _id The ID of the timestamp.
* @return An indication of whether or not a given timestamp is 'running'.
* @notice Even if this timestamp is not 'running', it is not necessarily 'expired'.
*/
function running(uint256 _id) external view returns (bool);
/**
* @dev Get an indication of whether or not a given timestamp is 'expired'.
* @param _id The ID of the timestamp.
* @return An indication of whether or not a given timestamp is 'expired'.
* @notice Even if this timestamp is not 'expired', it is not necessarily 'running'.
*/
function expired(uint256 _id) external view returns (bool);
}
// File: contracts/saga/interfaces/ISGAAuthorizationManager.sol
pragma solidity 0.4.25;
/**
* @title SGA Authorization Manager Interface.
*/
interface ISGAAuthorizationManager {
/**
* @dev Determine whether or not a user is authorized to buy SGA.
* @param _sender The address of the user.
* @return Authorization status.
*/
function isAuthorizedToBuy(address _sender) external view returns (bool);
/**
* @dev Determine whether or not a user is authorized to sell SGA.
* @param _sender The address of the user.
* @return Authorization status.
*/
function isAuthorizedToSell(address _sender) external view returns (bool);
/**
* @dev Determine whether or not a user is authorized to transfer SGA to another user.
* @param _sender The address of the source user.
* @param _target The address of the target user.
* @return Authorization status.
*/
function isAuthorizedToTransfer(address _sender, address _target) external view returns (bool);
/**
* @dev Determine whether or not a user is authorized to transfer SGA from one user to another user.
* @param _sender The address of the custodian user.
* @param _source The address of the source user.
* @param _target The address of the target user.
* @return Authorization status.
*/
function isAuthorizedToTransferFrom(address _sender, address _source, address _target) external view returns (bool);
/**
* @dev Determine whether or not a user is authorized for public operation.
* @param _sender The address of the user.
* @return Authorization status.
*/
function isAuthorizedForPublicOperation(address _sender) external view returns (bool);
}
// File: contracts/saga/interfaces/IMintListener.sol
pragma solidity 0.4.25;
/**
* @title Mint Listener Interface.
*/
interface IMintListener {
/**
* @dev Mint SGA for SGN holders.
* @param _value The amount of SGA to mint.
*/
function mintSgaForSgnHolders(uint256 _value) external;
}
// File: contracts/saga-genesis/interfaces/IMintHandler.sol
pragma solidity 0.4.25;
/**
* @title Mint Handler Interface.
*/
interface IMintHandler {
/**
* @dev Upon minting of SGN vested in delay.
* @param _index The minting-point index.
*/
function mintSgnVestedInDelay(uint256 _index) external;
}
// File: contracts/saga-genesis/interfaces/IMintManager.sol
pragma solidity 0.4.25;
/**
* @title Mint Manager Interface.
*/
interface IMintManager {
/**
* @dev Return the current minting-point index.
*/
function getIndex() external view returns (uint256);
}
// File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol
pragma solidity 0.4.25;
/**
* @title Contract Address Locator Interface.
*/
interface IContractAddressLocator {
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) external view returns (address);
/**
* @dev Determine whether or not a contract address is relates to one of the given identifiers.
* @param _contractAddress The contract address to look for.
* @param _identifiers The identifiers.
* @return Is the contract address relates to one of the identifiers.
*/
function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool);
}
// File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol
pragma solidity 0.4.25;
/**
* @title Contract Address Locator Holder.
* @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system.
* @dev Any contract which inherits from this contract can retrieve the address of any contract in the system.
* @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system.
* @dev In addition to that, any function in any contract can be restricted to a specific caller.
*/
contract ContractAddressLocatorHolder {
bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource";
bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ;
bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ;
bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ;
bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ;
bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ;
bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ;
bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ;
bytes32 internal constant _IMintHandler_ = "IMintHandler" ;
bytes32 internal constant _IMintListener_ = "IMintListener" ;
bytes32 internal constant _IMintManager_ = "IMintManager" ;
bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ;
bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ;
bytes32 internal constant _IRedButton_ = "IRedButton" ;
bytes32 internal constant _IReserveManager_ = "IReserveManager" ;
bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ;
bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ;
bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ;
bytes32 internal constant _ISGAAuthorizationManager_ = "ISGAAuthorizationManager";
bytes32 internal constant _ISGAToken_ = "ISGAToken" ;
bytes32 internal constant _ISGATokenManager_ = "ISGATokenManager" ;
bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager";
bytes32 internal constant _ISGNToken_ = "ISGNToken" ;
bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ;
bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ;
bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ;
bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ;
bytes32 internal constant _IWalletsTradingDataSource_ = "IWalletsTradingDataSource" ;
bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ;
bytes32 internal constant _WalletsTradingLimiter_SGATokenManager_ = "WalletsTLSGATokenManager" ;
bytes32 internal constant _IETHConverter_ = "IETHConverter" ;
bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ;
bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ;
bytes32 internal constant _IRateApprover_ = "IRateApprover" ;
IContractAddressLocator private contractAddressLocator;
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) internal {
require(_contractAddressLocator != address(0), "locator is illegal");
contractAddressLocator = _contractAddressLocator;
}
/**
* @dev Get the contract address locator.
* @return The contract address locator.
*/
function getContractAddressLocator() external view returns (IContractAddressLocator) {
return contractAddressLocator;
}
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) internal view returns (address) {
return contractAddressLocator.getContractAddress(_identifier);
}
/**
* @dev Determine whether or not the sender is relates to one of the identifiers.
* @param _identifiers The identifiers.
* @return Is the sender relates to one of the identifiers.
*/
function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) {
return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers);
}
/**
* @dev Verify that the caller is mapped to a given identifier.
* @param _identifier The identifier.
*/
modifier only(bytes32 _identifier) {
require(msg.sender == getContractAddress(_identifier), "caller is illegal");
_;
}
}
// File: contracts/saga/MintManager.sol
pragma solidity 0.4.25;
/**
* Details of usage of licenced software see here: https://www.saga.org/software/readme_v1
*/
/**
* @title Mint Manager.
*/
contract MintManager is IMintManager, ContractAddressLocatorHolder {
string public constant VERSION = "1.0.0";
uint256 public index;
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {}
/**
* @dev Return the contract which implements the IModelDataSource interface.
*/
function getModelDataSource() public view returns (IModelDataSource) {
return IModelDataSource(getContractAddress(_IModelDataSource_));
}
/**
* @dev Return the contract which implements the IMintingPointTimersManager interface.
*/
function getMintingPointTimersManager() public view returns (IMintingPointTimersManager) {
return IMintingPointTimersManager(getContractAddress(_IMintingPointTimersManager_));
}
/**
* @dev Return the contract which implements the ISGAAuthorizationManager interface.
*/
function getSGAAuthorizationManager() public view returns (ISGAAuthorizationManager) {
return ISGAAuthorizationManager(getContractAddress(_ISGAAuthorizationManager_));
}
/**
* @dev Return the contract which implements the IMintHandler interface.
*/
function getMintHandler() public view returns (IMintHandler) {
return IMintHandler(getContractAddress(_IMintHandler_));
}
/**
* @dev Return the contract which implements the IMintListener interface.
*/
function getMintListener() public view returns (IMintListener) {
return IMintListener(getContractAddress(_IMintListener_));
}
/**
* @dev Return whether or not the minting-state should be updated.
*/
function isMintingStateOutdated() public view returns (bool) {
return getMintingPointTimersManager().expired(index + 1);
}
/**
* @dev Update the minting-state if it is outdated.
*/
function updateMintingState() external {
require(getSGAAuthorizationManager().isAuthorizedForPublicOperation(msg.sender), "update minting state is not authorized");
if (isMintingStateOutdated()) {
uint256 amount = getModelDataSource().getRequiredMintAmount(index);
getMintListener().mintSgaForSgnHolders(amount);
getMintHandler().mintSgnVestedInDelay(index + 1);
index += 1;
}
}
/**
* @dev Return the current minting-point index.
*/
function getIndex() external view returns (uint256) {
return index;
}
} | * @title Mint Manager./ | contract MintManager is IMintManager, ContractAddressLocatorHolder {
string public constant VERSION = "1.0.0";
uint256 public index;
constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {}
function getModelDataSource() public view returns (IModelDataSource) {
return IModelDataSource(getContractAddress(_IModelDataSource_));
}
function getMintingPointTimersManager() public view returns (IMintingPointTimersManager) {
return IMintingPointTimersManager(getContractAddress(_IMintingPointTimersManager_));
}
function getSGAAuthorizationManager() public view returns (ISGAAuthorizationManager) {
return ISGAAuthorizationManager(getContractAddress(_ISGAAuthorizationManager_));
}
function getMintHandler() public view returns (IMintHandler) {
return IMintHandler(getContractAddress(_IMintHandler_));
}
function getMintListener() public view returns (IMintListener) {
return IMintListener(getContractAddress(_IMintListener_));
}
function isMintingStateOutdated() public view returns (bool) {
return getMintingPointTimersManager().expired(index + 1);
}
function updateMintingState() external {
require(getSGAAuthorizationManager().isAuthorizedForPublicOperation(msg.sender), "update minting state is not authorized");
if (isMintingStateOutdated()) {
uint256 amount = getModelDataSource().getRequiredMintAmount(index);
getMintListener().mintSgaForSgnHolders(amount);
getMintHandler().mintSgnVestedInDelay(index + 1);
index += 1;
}
}
function updateMintingState() external {
require(getSGAAuthorizationManager().isAuthorizedForPublicOperation(msg.sender), "update minting state is not authorized");
if (isMintingStateOutdated()) {
uint256 amount = getModelDataSource().getRequiredMintAmount(index);
getMintListener().mintSgaForSgnHolders(amount);
getMintHandler().mintSgnVestedInDelay(index + 1);
index += 1;
}
}
function getIndex() external view returns (uint256) {
return index;
}
} | 12,913,656 | [
1,
49,
474,
8558,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
490,
474,
1318,
353,
6246,
474,
1318,
16,
13456,
1887,
5786,
6064,
288,
203,
565,
533,
1071,
5381,
8456,
273,
315,
21,
18,
20,
18,
20,
14432,
203,
203,
565,
2254,
5034,
1071,
770,
31,
203,
203,
203,
203,
203,
565,
3885,
12,
45,
8924,
1887,
5786,
389,
16351,
1887,
5786,
13,
13456,
1887,
5786,
6064,
24899,
16351,
1887,
5786,
13,
1071,
2618,
203,
565,
445,
7454,
8597,
1435,
1071,
1476,
1135,
261,
45,
1488,
8597,
13,
288,
203,
3639,
327,
467,
1488,
8597,
12,
588,
8924,
1887,
24899,
45,
1488,
8597,
67,
10019,
203,
565,
289,
203,
203,
565,
445,
2108,
474,
310,
2148,
10178,
414,
1318,
1435,
1071,
1476,
1135,
261,
3445,
474,
310,
2148,
10178,
414,
1318,
13,
288,
203,
3639,
327,
6246,
474,
310,
2148,
10178,
414,
1318,
12,
588,
8924,
1887,
24899,
3445,
474,
310,
2148,
10178,
414,
1318,
67,
10019,
203,
565,
289,
203,
203,
565,
445,
1322,
25043,
6063,
1318,
1435,
1071,
1476,
1135,
261,
5127,
25043,
6063,
1318,
13,
288,
203,
3639,
327,
4437,
25043,
6063,
1318,
12,
588,
8924,
1887,
24899,
5127,
25043,
6063,
1318,
67,
10019,
203,
565,
289,
203,
203,
565,
445,
2108,
474,
1503,
1435,
1071,
1476,
1135,
261,
3445,
474,
1503,
13,
288,
203,
3639,
327,
6246,
474,
1503,
12,
588,
8924,
1887,
24899,
3445,
474,
1503,
67,
10019,
203,
565,
289,
203,
203,
565,
445,
2108,
474,
2223,
1435,
1071,
1476,
1135,
261,
3445,
474,
2223,
13,
288,
203,
3639,
327,
6246,
474,
2223,
12,
588,
8924,
1887,
24899,
2
] |
/*
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.
*/
// SPDX-License-Identifier: MIT
// import "hardhat/console.sol";
pragma solidity ^0.6.12;
library AddrArrayLib {
using AddrArrayLib for Addresses;
struct Addresses {
address[] _items;
mapping(address => int) map;
}
function removeAll(Addresses storage self) internal {
delete self._items;
}
function pushAddress(Addresses storage self, address element, bool allowDup) internal {
if (allowDup) {
self._items.push(element);
self.map[element] = 2;
} else if (!exists(self, element)) {
self._items.push(element);
self.map[element] = 2;
}
}
function removeAddress(Addresses storage self, address element) internal returns (bool) {
if (!exists(self, element)) {
return true;
}
for (uint i = 0; i < self.size(); i++) {
if (self._items[i] == element) {
self._items[i] = self._items[self.size() - 1];
self._items.pop();
self.map[element] = 1;
return true;
}
}
return false;
}
function getAddressAtIndex(Addresses storage self, uint256 index) internal view returns (address) {
require(index < size(self), "the index is out of bounds");
return self._items[index];
}
function size(Addresses storage self) internal view returns (uint256) {
return self._items.length;
}
function exists(Addresses storage self, address element) internal view returns (bool) {
return self.map[element] == 2;
}
function getAllAddresses(Addresses storage self) internal view returns (address[] memory) {
return self._items;
}
}
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);
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
// silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {codehash := extcodehash(account)}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{value : amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value : weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
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;
}
}
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;
}
interface IERC2612 {
/**
* @dev Returns the current ERC2612 nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
}
interface IAnyswapV3ERC20 is IERC20, IERC2612 {
/// @dev Sets `value` as allowance of `spender` account over caller account's AnyswapV3ERC20 token,
/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.
/// Emits {Approval} event.
/// Returns boolean value indicating whether operation succeeded.
/// For more information on approveAndCall format, see https://github.com/ethereum/EIPs/issues/677.
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
/// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`),
/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.
/// A transfer to `address(0)` triggers an ERC-20 withdraw matching the sent AnyswapV3ERC20 token in favor of caller.
/// Emits {Transfer} event.
/// Returns boolean value indicating whether operation succeeded.
/// Requirements:
/// - caller account must have at least `value` AnyswapV3ERC20 token.
/// For more information on transferAndCall format, see https://github.com/ethereum/EIPs/issues/677.
function transferAndCall(address to, uint value, bytes calldata data) external returns (bool);
}
interface ITransferReceiver {
function onTokenTransfer(address, uint, bytes calldata) external returns (bool);
}
interface IApprovalReceiver {
function onTokenApproval(address, uint, bytes calldata) external returns (bool);
}
contract Token is IAnyswapV3ERC20, Context, Ownable {
using SafeMath for uint256;
using Address for address;
using AddrArrayLib for AddrArrayLib.Addresses;
mapping (address => uint256) public override nonces;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => bool) public _isExcluded;
mapping(address => bool) public whitelist;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1_000_000_000_000_000_000_000;
uint256 public _maxTxAmount = 10_000_000_000_000_000_000; // 10b
uint256 private numTokensSellToAddToLiquidity = 1_000_000_000_000_000; // 1m
// mint transfer value to get a ticket
uint256 public minimumDonationForTicket = 1_000_000_000_000_000_000; // 1b
uint256 public lotteryHolderMinBalance = 1_000_000_000_000_000_000; // 1b
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "Elonson Inu";
string private _symbol = "ESI";
uint8 public immutable decimals = 9;
address public donationAddress = 0x676FbD4E4bd54e3a1Be74178df2fFefa15B4824b;
address public holderAddress = 0xa30d530C0BCB6f7b7D5a83B1D51716d7eeaf8E8F;
address public burnAddress = 0x000000000000000000000000000000000000dEaD;
address public charityWalletAddress = 0x37c636084cf1d5e0a23dc6eAadcD2a93eF00E0c1;
address public devFundWalletAddress = 0xd68749450a51e50e4418F13fB3cEaBB27B2e68aB;
address public marketingFundWalletAddress = 0x6EAe593726Cdc7fe4249CF77a1B5B24f0bd3dB11;
address public donationLotteryPrizeWalletAddress = 0xa4c57d4bf1dEf34f40A15d8B89d3cCb315722d7F;
address public faaSWalletAddress = 0xfC1034EFFE7A26a0FD69B5c08b21d1e0855fdb19;
uint256 public _FaaSFee = 10; //1%
uint256 private _previous_FaaSFee = _FaaSFee;
uint256 public _distributionFee = 10; //1%
uint256 private _previousDistributionFee = _distributionFee;
uint256 public _charityFee = 20; //2%
uint256 private _previousCharityFee = _charityFee;
uint256 public _devFundFee = 10; //1%
uint256 private _previousDevFundFee = _devFundFee;
uint256 public _marketingFundFee = 10; //1%
uint256 private _previousMarketingFundFee = _marketingFundFee;
uint256 public _donationLotteryPrizeFee = 5; //0.5%
uint256 private _previousDonationLotteryPrizeFee = _donationLotteryPrizeFee;
uint256 public _burnFee = 10; //1%
uint256 private _previousBurnFee = _burnFee;
uint256 public _lotteryHolderFee = 5; //0.5%
uint256 private _previousLotteryHolderFee = _lotteryHolderFee;
uint256 public _liquidityFee = 10; //1%
uint256 private _previousLiquidityFee = _liquidityFee;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public _creationTime = now;
uint256 public endtime; // when lottery period end and prize get distributed
mapping(address => uint256) public userTicketsTs;
bool public disableTicketsTs = false; // disable on testing env only
bool public donationLotteryDebug = true; // disable on testing env only
bool public donationLotteryEnabled = true;
address[] private donationLotteryUsers; // list of tickets for 1000 tx prize
uint256 public donationLotteryIndex; // index of last winner
address public donationLotteryWinner; // last random winner
uint256 public donationLotteryLimit = 1000;
uint256 public donationLotteryMinLimit = 50;
bool public lotteryHoldersEnabled = true;
bool public lotteryHoldersDebug = true;
uint256 public lotteryHoldersLimit = 1000;
uint256 public lotteryHoldersIndex = 0;
address public lotteryHoldersWinner;
// list of balance by users illegible for holder lottery
AddrArrayLib.Addresses private ticketsByBalance;
event LotteryHolderChooseOne(uint256 tickets, address winner, uint256 prize);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
// control % of a buy in the first days
uint antiAbuseDay1 = 50; // 0.5%
uint antiAbuseDay2 = 100; // 1.0%
uint antiAbuseDay3 = 150; // 1.5%
constructor (address mintSupplyTo, address router) public {
//console.log('_tTotal=%s', _tTotal);
_rOwned[mintSupplyTo] = _rTotal;
// we whitelist treasure and owner to allow pool management
whitelist[mintSupplyTo] = true;
whitelist[owner()] = true;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(router);
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[mintSupplyTo] = true;
_isExcludedFromFee[donationLotteryPrizeWalletAddress] = true;
_isExcludedFromFee[donationAddress] = true;
_isExcludedFromFee[devFundWalletAddress] = true;
_isExcludedFromFee[marketingFundWalletAddress] = true;
_isExcludedFromFee[holderAddress] = true;
_isExcludedFromFee[charityWalletAddress] = true;
_isExcludedFromFee[burnAddress] = true;
_isExcludedFromFee[faaSWalletAddress] = true;
emit Transfer(address(0), mintSupplyTo, _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function approveAndCall(address spender, uint256 value, bytes calldata data) external override returns (bool) {
// _approve(msg.sender, spender, value);
_allowances[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return IApprovalReceiver(spender).onTokenApproval(msg.sender, value, data);
}
/// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`),
/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.
/// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller.
/// Emits {Transfer} event.
/// Returns boolean value indicating whether operation succeeded.
/// Requirements:
/// - caller account must have at least `value` AnyswapV3ERC20 token.
/// For more information on transferAndCall format, see https://github.com/ethereum/EIPs/issues/677.
function transferAndCall(address to, uint value, bytes calldata data) external override returns (bool) {
require(to != address(0) || to != address(this));
_transfer(msg.sender, to, value);
return ITransferReceiver(to).onTokenTransfer(msg.sender, value, data);
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(rInfo memory rr,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rr.rAmount);
_rTotal = _rTotal.sub(rr.rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(rInfo memory rr,) = _getValues(tAmount);
return rr.rAmount;
} else {
(rInfo memory rr,) = _getValues(tAmount);
return rr.rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns (uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(rInfo memory rr, tInfo memory tt) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rr.rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tt.tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rr.rTransferAmount);
_takeLiquidity(tt.tLiquidity);
_reflectFee(rr, tt);
emit Transfer(sender, recipient, tt.tTransferAmount);
}
// whitelist to add liquidity
function setWhitelist(address account, bool _status) public onlyOwner {
whitelist[account] = _status;
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setDistributionFeePercent(uint256 distributionFee) external onlyOwner() {
_distributionFee = distributionFee;
}
function setCharityFeePercent(uint256 charityFee) external onlyOwner() {
_charityFee = charityFee;
}
function setDevFundFeePercent(uint256 devFundFee) external onlyOwner() {
_devFundFee = devFundFee;
}
function setMarketingFundFeePercent(uint256 marketingFundFee) external onlyOwner() {
_marketingFundFee = marketingFundFee;
}
function setDonationLotteryPrizeFeePercent(uint256 donationLotteryPrizeFee) external onlyOwner() {
_donationLotteryPrizeFee = donationLotteryPrizeFee;
}
function setBurnFeePercent(uint256 burnFee) external onlyOwner() {
_burnFee = burnFee;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() {
_liquidityFee = liquidityFee;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(
10 ** 2
);
}
event SwapAndLiquifyEnabledUpdated(bool _enabled);
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _reflectFee(rInfo memory rr, tInfo memory tt) private {
_rTotal = _rTotal.sub(rr.rDistributionFee);
_tFeeTotal = _tFeeTotal.add(tt.tDistributionFee).add(tt.tCharityFee).add(tt.tDevFundFee)
.add(tt.tMarketingFundFee).add(tt.tDonationLotteryPrizeFee).add(tt.tBurn).add(tt.tHolderFee).add(tt.tFaaSFee);
_rOwned[holderAddress] = _rOwned[holderAddress].add(rr.rHolderFee);
_rOwned[charityWalletAddress] = _rOwned[charityWalletAddress].add(rr.rCharityFee);
_rOwned[devFundWalletAddress] = _rOwned[devFundWalletAddress].add(rr.rDevFundFee);
_rOwned[marketingFundWalletAddress] = _rOwned[marketingFundWalletAddress].add(rr.rMarketingFundFee);
_rOwned[donationLotteryPrizeWalletAddress] = _rOwned[donationLotteryPrizeWalletAddress].add(rr.rDonationLotteryPrizeFee);
_rOwned[burnAddress] = _rOwned[burnAddress].add(rr.rBurn);
_rOwned[faaSWalletAddress] = _rOwned[faaSWalletAddress].add(rr.rFaaSFee);
if( tt.tHolderFee > 0)
emit Transfer(msg.sender, holderAddress, tt.tHolderFee);
if( tt.tCharityFee > 0)
emit Transfer(msg.sender, charityWalletAddress, tt.tCharityFee);
if( tt.tDevFundFee > 0 )
emit Transfer(msg.sender, devFundWalletAddress, tt.tDevFundFee);
if( tt.tMarketingFundFee > 0 )
emit Transfer(msg.sender, marketingFundWalletAddress, tt.tMarketingFundFee);
if( tt.tDonationLotteryPrizeFee > 0 )
emit Transfer(msg.sender, donationLotteryPrizeWalletAddress, tt.tDonationLotteryPrizeFee);
if( tt.tBurn > 0 )
emit Transfer(msg.sender, burnAddress, tt.tBurn);
if( tt.tFaaSFee > 0 )
emit Transfer(msg.sender, faaSWalletAddress, tt.tFaaSFee);
}
struct tInfo {
uint256 tTransferAmount;
uint256 tDistributionFee;
uint256 tLiquidity;
uint256 tCharityFee;
uint256 tDevFundFee;
uint256 tMarketingFundFee;
uint256 tDonationLotteryPrizeFee;
uint256 tBurn;
uint256 tHolderFee;
uint256 tFaaSFee;
}
struct rInfo {
uint256 rAmount;
uint256 rTransferAmount;
uint256 rDistributionFee;
uint256 rCharityFee;
uint256 rDevFundFee;
uint256 rMarketingFundFee;
uint256 rDonationLotteryPrizeFee;
uint256 rBurn;
uint256 rLiquidity;
uint256 rHolderFee;
uint256 rFaaSFee;
}
function _getValues(uint256 tAmount) private view returns (rInfo memory rr, tInfo memory tt) {
tt = _getTValues(tAmount);
rr = _getRValues(tAmount, tt.tDistributionFee, tt.tCharityFee, tt.tDevFundFee, tt.tMarketingFundFee,
tt.tDonationLotteryPrizeFee, tt.tBurn, tt.tHolderFee, tt.tLiquidity, _getRate(), tt.tFaaSFee);
return (rr, tt);
}
function _getTValues(uint256 tAmount) private view returns (tInfo memory tt) {
tt.tFaaSFee = calculateFaaSFee(tAmount); // _FaaSFee 1%
tt.tDistributionFee = calculateDistributionFee(tAmount); // _distributionFee 1%
tt.tCharityFee = calculateCharityFee(tAmount); // _charityFee 2%
tt.tDevFundFee = calculateDevFundFee(tAmount); // _devFundFee 1%
tt.tMarketingFundFee = calculateMarketingFundFee(tAmount); // _marketingFundFee 1%
tt.tDonationLotteryPrizeFee = calculateDonationLotteryPrizeFee(tAmount); // _donationLotteryPrizeFee 0.5%
tt.tBurn = calculateBurnFee(tAmount); // _burnFee 1%
tt.tHolderFee = calculateHolderFee(tAmount); // _lotteryHolderFee 0.5%
tt.tLiquidity = calculateLiquidityFee(tAmount); // _liquidityFee 1%
uint totalFee = tt.tDistributionFee.add(tt.tCharityFee).add(tt.tDevFundFee)
.add(tt.tMarketingFundFee).add(tt.tDonationLotteryPrizeFee).add(tt.tBurn);
totalFee = totalFee.add(tt.tLiquidity).add(tt.tHolderFee).add(tt.tFaaSFee);
tt.tTransferAmount = tAmount.sub(totalFee);
return tt;
}
function _getRValues(uint256 tAmount, uint256 tDistributionFee, uint256 tCharityFee, uint256 tDevFundFee,
uint256 tMarketingFundFee, uint256 tDonationLotteryPrizeFee, uint256 tBurn, uint256 tHolderFee, uint256 tLiquidity,
uint256 currentRate, uint256 tFaaSFee) private pure returns (rInfo memory rr) {
rr.rAmount = tAmount.mul(currentRate);
rr.rDistributionFee = tDistributionFee.mul(currentRate);
rr.rCharityFee = tCharityFee.mul(currentRate);
rr.rDevFundFee = tDevFundFee.mul(currentRate);
rr.rMarketingFundFee = tMarketingFundFee.mul(currentRate);
rr.rDonationLotteryPrizeFee = tDonationLotteryPrizeFee.mul(currentRate);
rr.rBurn = tBurn.mul(currentRate);
rr.rLiquidity = tLiquidity.mul(currentRate);
rr.rHolderFee = tHolderFee.mul(currentRate);
rr.rFaaSFee = tFaaSFee.mul(currentRate);
uint totalFee = rr.rDistributionFee.add(rr.rCharityFee).add(rr.rDevFundFee).add(rr.rMarketingFundFee);
totalFee = totalFee.add(rr.rDonationLotteryPrizeFee).add(rr.rBurn).add(rr.rLiquidity).add(rr.rHolderFee).add(rr.rFaaSFee);
rr.rTransferAmount = rr.rAmount.sub(totalFee);
return rr;
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if (_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateDistributionFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_distributionFee).div(1000);
}
function calculateCharityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_charityFee).div(1000);
}
function calculateDevFundFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_devFundFee).div(1000);
}
function calculateMarketingFundFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_marketingFundFee).div(1000);
}
function calculateDonationLotteryPrizeFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_donationLotteryPrizeFee).div(1000);
}
function calculateBurnFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_burnFee).div(1000);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(1000);
}
function calculateHolderFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_lotteryHolderFee).div(1000);
}
function calculateFaaSFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_FaaSFee).div(1000);
}
function removeAllFee() private {
_previousDistributionFee = _distributionFee;
_previousLiquidityFee = _liquidityFee;
_previous_FaaSFee = _FaaSFee;
_previousCharityFee = _charityFee;
_previousDevFundFee = _devFundFee;
_previousMarketingFundFee = _marketingFundFee;
_previousDonationLotteryPrizeFee = _donationLotteryPrizeFee;
_previousBurnFee = _burnFee;
_previousLotteryHolderFee = _lotteryHolderFee;
_FaaSFee = 0;
_distributionFee = 0;
_charityFee = 0;
_devFundFee = 0;
_marketingFundFee = 0;
_donationLotteryPrizeFee = 0;
_burnFee = 0;
_liquidityFee = 0;
_lotteryHolderFee = 0;
}
function restoreAllFee() private {
_FaaSFee = _previous_FaaSFee;
_distributionFee = _previousDistributionFee;
_charityFee = _previousCharityFee;
_devFundFee = _previousDevFundFee;
_marketingFundFee = _previousMarketingFundFee;
_donationLotteryPrizeFee = _previousDonationLotteryPrizeFee;
_burnFee = _previousBurnFee;
_liquidityFee = _previousLiquidityFee;
_lotteryHolderFee = _previousLotteryHolderFee;
}
function isExcludedFromFee(address account) public view returns (bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _antiAbuse(address from, address to, uint256 amount) private view {
if (from == owner() || to == owner())
// if owner we just return or we can't add liquidity
return;
uint256 allowedAmount;
(, uint256 tSupply) = _getCurrentSupply();
uint256 lastUserBalance = balanceOf(to) + (amount * (10000 - getTotalFees()) / 10000);
// bot \ whales prevention
if (now <= (_creationTime.add(1 days))) {
allowedAmount = tSupply.mul(antiAbuseDay1).div(10000);
// bool s = lastUserBalance < allowedAmount;
//console.log('lastUserBalance = %s', lastUserBalance);
//console.log('allowedAmount = %s status=', allowedAmount, s);
require(lastUserBalance < allowedAmount, "Transfer amount exceeds the max for day 1");
} else if (now <= (_creationTime.add(2 days))) {
allowedAmount = tSupply.mul(antiAbuseDay2).div(10000);
require(lastUserBalance < allowedAmount, "Transfer amount exceeds the max for day 2");
} else if (now <= (_creationTime.add(3 days))) {
allowedAmount = tSupply.mul(antiAbuseDay3).div(10000);
require(lastUserBalance < allowedAmount, "Transfer amount exceeds the max for day 3");
}
}
event WhiteListTransfer(address from, address to, uint256 amount);
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
uint256 contractTokenBalance = balanceOf(address(this));
// whitelist to allow treasure to add liquidity:
if (whitelist[from] || whitelist[to]) {
emit WhiteListTransfer(from, to, amount);
} else {
if( from == uniswapV2Pair || from == address(uniswapV2Router) ){
_antiAbuse(from, to, amount);
}
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
if (contractTokenBalance >= _maxTxAmount) {
contractTokenBalance = _maxTxAmount;
}
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
//add liquidity
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from, to, amount, takeFee);
// process lottery if user is paying fee
lotteryOnTransfer(from, to, amount);
}
event SwapAndLiquify(uint256 half, uint256 newBalance, uint256 otherHalf);
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// split the contract balance into halves
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half);
// <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value : ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if (!takeFee) {
removeAllFee();
}
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if (!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(rInfo memory rr, tInfo memory tt) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rr.rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rr.rTransferAmount);
_takeLiquidity(tt.tLiquidity);
_reflectFee(rr, tt);
emit Transfer(sender, recipient, tt.tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(rInfo memory rr, tInfo memory tt) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rr.rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tt.tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rr.rTransferAmount);
_takeLiquidity(tt.tLiquidity);
_reflectFee(rr, tt);
emit Transfer(sender, recipient, tt.tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(rInfo memory rr, tInfo memory tt) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rr.rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rr.rTransferAmount);
_takeLiquidity(tt.tLiquidity);
_reflectFee(rr, tt);
emit Transfer(sender, recipient, tt.tTransferAmount);
}
function getTime() public view returns (uint256){
return block.timestamp;
}
function getTotalFees() internal view returns (uint256) {
return _charityFee + _liquidityFee + _burnFee + _donationLotteryPrizeFee + _marketingFundFee + _devFundFee;
}
function getPrizeForEach1k() public view returns (uint256) {
return balanceOf(donationLotteryPrizeWalletAddress);
}
function getPrizeForHolders() public view returns (uint256) {
return balanceOf(holderAddress);
}
// view to get illegible holders lottery
function getTicketsByBalance() public view returns (address[] memory){
return ticketsByBalance.getAllAddresses();
}
function setLotteryHoldersLimit(uint256 val) public onlyOwner {
lotteryHoldersLimit = val;
}
function setDisableTicketsTs(bool status) public onlyOwner {
disableTicketsTs = status;
}
function setLotteryHolderMinBalance(uint256 val) public onlyOwner {
lotteryHolderMinBalance = val;
}
function setMinimumDonationForTicket(uint256 val) public onlyOwner {
minimumDonationForTicket = val;
}
function setLotteryHoldersEnabled(bool val) public onlyOwner {
lotteryHoldersEnabled = val;
}
function lotteryUserTickets(address _user) public view returns (uint256[] memory){
uint[] memory my = new uint256[](donationLotteryUsers.length);
uint count;
for (uint256 i = 0; i < donationLotteryUsers.length; i++) {
if (donationLotteryUsers[i] == _user) {
my[count++] = i;
}
}
return my;
}
function lotteryTotalTicket() public view returns (uint256){
return donationLotteryUsers.length;
}
// process both lottery
function lotteryOnTransfer(address user, address to, uint256 value) internal {
if( donationLotteryEnabled ){
donationLottery(user, to, value);
}
if( lotteryHoldersEnabled ){
lotteryHolders(user, to);
}
}
// 0.5% for holders of certain amount of tokens for random chance every 1000 tx
// lottery that get triggered on N number of TX
event donationLotteryTicket(address user, address to, uint256 value, uint256 donationLotteryIndex, uint256 donationLotteryUsers);
event LotteryTriggerEveryNtx(uint256 ticket, address winner, uint256 prize);
function setDonationLotteryLimit(uint256 val) public onlyOwner {
donationLotteryLimit = val;
}
function setDonationLotteryMinLimit(uint256 val) public onlyOwner {
donationLotteryMinLimit = val;
}
function setDonationLotteryEnabled(bool val) public onlyOwner {
donationLotteryEnabled = val;
}
function setDonationLotteryDebug(bool val) public onlyOwner {
donationLotteryDebug = val;
}
function setLotteryHoldersDebug(bool val) public onlyOwner {
lotteryHoldersDebug = val;
}
function donationLottery(address user, address to, uint256 value) internal {
uint256 prize = getPrizeForEach1k();
if (value >= minimumDonationForTicket && to == donationAddress) {
// if(donationLotteryDebug) console.log("- donationLottery> donation=%s value=%d donationLotteryLimit=%d", donationLotteryPrizeWalletAddress, value, donationLotteryLimit);
uint256 uts = userTicketsTs[user];
if (disableTicketsTs == false || uts == 0 || uts.add(3600) <= block.timestamp) {
donationLotteryIndex++;
donationLotteryUsers.push(user);
userTicketsTs[user] = block.timestamp;
emit donationLotteryTicket(user, to, value, donationLotteryIndex, donationLotteryUsers.length);
// if(donationLotteryDebug) console.log("\tdonationLottery> added index=%d length=%d prize=%d", donationLotteryIndex, donationLotteryUsers.length, prize);
}
}
// console.log("prize=%d index=%d limit =%d", prize, donationLotteryIndex, donationLotteryLimit);
if (prize > 0 && donationLotteryIndex >= donationLotteryLimit) {
uint256 _mod = donationLotteryUsers.length;
// console.log("\tlength=%d limist=%d", donationLotteryUsers.length, donationLotteryMinLimit);
if (donationLotteryUsers.length < donationLotteryMinLimit){
return;
}
uint256 _randomNumber;
bytes32 _structHash = keccak256(abi.encode(msg.sender, block.difficulty, gasleft(), prize));
_randomNumber = uint256(_structHash);
assembly {_randomNumber := mod(_randomNumber, _mod)}
donationLotteryWinner = donationLotteryUsers[_randomNumber];
emit LotteryTriggerEveryNtx(_randomNumber, donationLotteryWinner, prize);
_tokenTransfer(donationLotteryPrizeWalletAddress, donationLotteryWinner, prize, false);
// if(donationLotteryDebug){
// console.log("\t\tdonationLottery> TRIGGER _mod=%d rnd=%d prize=%d", _mod, _randomNumber, prize);
// console.log("\t\tdonationLottery> TRIGGER winner=%s", donationLotteryWinner);
// }
donationLotteryIndex = 0;
delete donationLotteryUsers;
}
}
// add and remove users according to their balance from holder lottery
//event LotteryAddToHolder(address from, bool status);
function addUserToBalanceLottery(address user) internal {
if (!_isExcludedFromFee[user] && !_isExcluded[user] ){
uint256 balance = balanceOf(user);
bool exists = ticketsByBalance.exists(user);
// emit LotteryAddToHolder(user, exists);
if (balance >= lotteryHolderMinBalance && !exists) {
ticketsByBalance.pushAddress(user, false);
// if(lotteryHoldersDebug)
// console.log("\t\tADD %s HOLDERS=%d PRIZE=%d", user, ticketsByBalance.size(), getPrizeForHolders()/1e9);
} else if (balance < lotteryHolderMinBalance && exists) {
ticketsByBalance.removeAddress(user);
// if(lotteryHoldersDebug)
// console.log("\t\tREMOVE HOLDERS=%d PRIZE=%d", ticketsByBalance.size(), getPrizeForHolders()/1e9);
}
}
}
function lotteryHolders(address user, address to) internal {
uint256 prize = getPrizeForHolders();
if( user != address(uniswapV2Router) && user != uniswapV2Pair ){
addUserToBalanceLottery(user);
}
if( to != address(uniswapV2Router) && to != uniswapV2Pair ){
addUserToBalanceLottery(to);
}
// if(lotteryHoldersDebug){
// console.log("\tTICKETS=%d PRIZE=%d, INDEX=%d", ticketsByBalance.size(), prize/1e9, lotteryHoldersIndex );
// }
if (prize > 0 && lotteryHoldersIndex >= lotteryHoldersLimit && ticketsByBalance.size() > 0 ) {
uint256 _mod = ticketsByBalance.size() - 1;
uint256 _randomNumber;
bytes32 _structHash = keccak256(abi.encode(msg.sender, block.difficulty, gasleft()));
_randomNumber = uint256(_structHash);
assembly {_randomNumber := mod(_randomNumber, _mod)}
lotteryHoldersWinner = ticketsByBalance._items[_randomNumber];
// console.log("%s %s %s", lotteryHoldersWinner, _randomNumber, ticketsByBalance.size());
emit LotteryHolderChooseOne(ticketsByBalance.size(), lotteryHoldersWinner, prize);
_tokenTransfer(holderAddress, lotteryHoldersWinner, prize, false);
// if(lotteryHoldersDebug){
// console.log("\t\tPRIZE=%d index=%d lmt=%d", prize/1e9, lotteryHoldersIndex, lotteryHoldersLimit);
// console.log("\t\tlotteryHoldersWinner=%s rnd=", lotteryHoldersWinner, _randomNumber);
// }
lotteryHoldersIndex = 0;
}
lotteryHoldersIndex++;
}
function setDonationAddress(address val) public onlyOwner {
donationAddress = val;
}
function setHolderAddress(address val) public onlyOwner {
holderAddress = val;
}
function setBurnAddress(address val) public onlyOwner {
burnAddress = val;
}
function setCharityWalletAddress(address val) public onlyOwner {
charityWalletAddress = val;
}
function setDevFundWalletAddress(address val) public onlyOwner {
devFundWalletAddress = val;
}
function setMarketingFundWalletAddress(address val) public onlyOwner {
marketingFundWalletAddress = val;
}
function setDonationLotteryPrizeWalletAddress(address val) public onlyOwner {
donationLotteryPrizeWalletAddress = val;
}
function setFaaSWalletAddress(address val) public onlyOwner {
faaSWalletAddress = val;
}
function updateHolderList(address[] memory holdersToCheck) public onlyOwner {
for( uint i = 0 ; i < holdersToCheck.length ; i ++ ){
addUserToBalanceLottery(holdersToCheck[i]);
}
}
} | console.log('_tTotal=%s', _tTotal); we whitelist treasure and owner to allow pool management Create a uniswap pair for this new token set the rest of the contract variablesexclude owner and this contract from fee | constructor (address mintSupplyTo, address router) public {
_rOwned[mintSupplyTo] = _rTotal;
whitelist[mintSupplyTo] = true;
whitelist[owner()] = true;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(router);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[mintSupplyTo] = true;
_isExcludedFromFee[donationLotteryPrizeWalletAddress] = true;
_isExcludedFromFee[donationAddress] = true;
_isExcludedFromFee[devFundWalletAddress] = true;
_isExcludedFromFee[marketingFundWalletAddress] = true;
_isExcludedFromFee[holderAddress] = true;
_isExcludedFromFee[charityWalletAddress] = true;
_isExcludedFromFee[burnAddress] = true;
_isExcludedFromFee[faaSWalletAddress] = true;
emit Transfer(address(0), mintSupplyTo, _tTotal);
}
| 1,564,433 | [
1,
8698,
18,
1330,
2668,
67,
88,
5269,
5095,
87,
2187,
389,
88,
5269,
1769,
732,
10734,
9787,
3619,
471,
3410,
358,
1699,
2845,
11803,
1788,
279,
640,
291,
91,
438,
3082,
364,
333,
394,
1147,
444,
326,
3127,
434,
326,
6835,
3152,
10157,
3410,
471,
333,
6835,
628,
14036,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
261,
2867,
312,
474,
3088,
1283,
774,
16,
1758,
4633,
13,
1071,
288,
203,
3639,
389,
86,
5460,
329,
63,
81,
474,
3088,
1283,
774,
65,
273,
389,
86,
5269,
31,
203,
203,
3639,
10734,
63,
81,
474,
3088,
1283,
774,
65,
273,
638,
31,
203,
3639,
10734,
63,
8443,
1435,
65,
273,
638,
31,
203,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
10717,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
3639,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
8443,
1435,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
81,
474,
3088,
1283,
774,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
19752,
367,
48,
352,
387,
93,
2050,
554,
16936,
1887,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
19752,
367,
1887,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
2
] |
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 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: REMIX_FILE_SYNC/ApprovedCreatorRegistryInterface.sol
pragma solidity ^0.4.22;
/**
* Interface to the digital media store external contract that is
* responsible for storing the common digital media and collection data.
* This allows for new token contracts to be deployed and continue to reference
* the digital media and collection data.
*/
contract ApprovedCreatorRegistryInterface {
function getVersion() public pure returns (uint);
function typeOfContract() public pure returns (string);
function isOperatorApprovedForCustodialAccount(
address _operator,
address _custodialAddress) public view returns (bool);
}
// File: REMIX_FILE_SYNC/DigitalMediaStoreInterface.sol
pragma solidity 0.4.25;
/**
* Interface to the digital media store external contract that is
* responsible for storing the common digital media and collection data.
* This allows for new token contracts to be deployed and continue to reference
* the digital media and collection data.
*/
contract DigitalMediaStoreInterface {
function getDigitalMediaStoreVersion() public pure returns (uint);
function getStartingDigitalMediaId() public view returns (uint256);
function registerTokenContractAddress() external;
/**
* Creates a new digital media object in storage
* @param _creator address the address of the creator
* @param _printIndex uint32 the current print index for the limited edition media
* @param _totalSupply uint32 the total allowable prints for this media
* @param _collectionId uint256 the collection id that this media belongs to
* @param _metadataPath string the ipfs metadata path
* @return the id of the new digital media created
*/
function createDigitalMedia(
address _creator,
uint32 _printIndex,
uint32 _totalSupply,
uint256 _collectionId,
string _metadataPath) external returns (uint);
/**
* Increments the current print index of the digital media object
* @param _digitalMediaId uint256 the id of the digital media
* @param _increment uint32 the amount to increment by
*/
function incrementDigitalMediaPrintIndex(
uint256 _digitalMediaId,
uint32 _increment) external;
/**
* Retrieves the digital media object by id
* @param _digitalMediaId uint256 the address of the creator
*/
function getDigitalMedia(uint256 _digitalMediaId) external view returns(
uint256 id,
uint32 totalSupply,
uint32 printIndex,
uint256 collectionId,
address creator,
string metadataPath);
/**
* Creates a new collection
* @param _creator address the address of the creator
* @param _metadataPath string the ipfs metadata path
* @return the id of the new collection created
*/
function createCollection(address _creator, string _metadataPath) external returns (uint);
/**
* Retrieves a collection by id
* @param _collectionId uint256
*/
function getCollection(uint256 _collectionId) external view
returns(
uint256 id,
address creator,
string metadataPath);
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.4.21;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.4.21;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: REMIX_FILE_SYNC/MediaStoreVersionControl.sol
pragma solidity 0.4.25;
/**
* A special control class that is used to configure and manage a token contract's
* different digital media store versions.
*
* Older versions of token contracts had the ability to increment the digital media's
* print edition in the media store, which was necessary in the early stages to provide
* upgradeability and flexibility.
*
* New verions will get rid of this ability now that token contract logic
* is more stable and we've built in burn capabilities.
*
* In order to support the older tokens, we need to be able to look up the appropriate digital
* media store associated with a given digital media id on the latest token contract.
*/
contract MediaStoreVersionControl is Pausable {
// The single allowed creator for this digital media contract.
DigitalMediaStoreInterface public v1DigitalMediaStore;
// The current digitial media store, used for this tokens creation.
DigitalMediaStoreInterface public currentDigitalMediaStore;
uint256 public currentStartingDigitalMediaId;
/**
* Validates that the managers are initialized.
*/
modifier managersInitialized() {
require(v1DigitalMediaStore != address(0));
require(currentDigitalMediaStore != address(0));
_;
}
/**
* Sets a digital media store address upon construction.
* Once set it's immutable, so that a token contract is always
* tied to one digital media store.
*/
function setDigitalMediaStoreAddress(address _dmsAddress)
internal {
DigitalMediaStoreInterface candidateDigitalMediaStore = DigitalMediaStoreInterface(_dmsAddress);
require(candidateDigitalMediaStore.getDigitalMediaStoreVersion() == 2, "Incorrect version.");
currentDigitalMediaStore = candidateDigitalMediaStore;
currentDigitalMediaStore.registerTokenContractAddress();
currentStartingDigitalMediaId = currentDigitalMediaStore.getStartingDigitalMediaId();
}
/**
* Publicly callable by the owner, but can only be set one time, so don't make
* a mistake when setting it.
*
* Will also check that the version on the other end of the contract is in fact correct.
*/
function setV1DigitalMediaStoreAddress(address _dmsAddress) public onlyOwner {
require(address(v1DigitalMediaStore) == 0, "V1 media store already set.");
DigitalMediaStoreInterface candidateDigitalMediaStore = DigitalMediaStoreInterface(_dmsAddress);
require(candidateDigitalMediaStore.getDigitalMediaStoreVersion() == 1, "Incorrect version.");
v1DigitalMediaStore = candidateDigitalMediaStore;
v1DigitalMediaStore.registerTokenContractAddress();
}
/**
* Depending on the digital media id, determines whether to return the previous
* version of the digital media manager.
*/
function _getDigitalMediaStore(uint256 _digitalMediaId)
internal
view
managersInitialized
returns (DigitalMediaStoreInterface) {
if (_digitalMediaId < currentStartingDigitalMediaId) {
return v1DigitalMediaStore;
} else {
return currentDigitalMediaStore;
}
}
}
// File: REMIX_FILE_SYNC/DigitalMediaManager.sol
pragma solidity 0.4.25;
/**
* Manager that interfaces with the underlying digital media store contract.
*/
contract DigitalMediaManager is MediaStoreVersionControl {
struct DigitalMedia {
uint256 id;
uint32 totalSupply;
uint32 printIndex;
uint256 collectionId;
address creator;
string metadataPath;
}
struct DigitalMediaCollection {
uint256 id;
address creator;
string metadataPath;
}
ApprovedCreatorRegistryInterface public creatorRegistryStore;
// Set the creator registry address upon construction. Immutable.
function setCreatorRegistryStore(address _crsAddress) internal {
ApprovedCreatorRegistryInterface candidateCreatorRegistryStore = ApprovedCreatorRegistryInterface(_crsAddress);
require(candidateCreatorRegistryStore.getVersion() == 1);
// Simple check to make sure we are adding the registry contract indeed
// https://fravoll.github.io/solidity-patterns/string_equality_comparison.html
require(keccak256(candidateCreatorRegistryStore.typeOfContract()) == keccak256("approvedCreatorRegistry"));
creatorRegistryStore = candidateCreatorRegistryStore;
}
/**
* Validates that the Registered store is initialized.
*/
modifier registryInitialized() {
require(creatorRegistryStore != address(0));
_;
}
/**
* Retrieves a collection object by id.
*/
function _getCollection(uint256 _id)
internal
view
managersInitialized
returns(DigitalMediaCollection) {
uint256 id;
address creator;
string memory metadataPath;
(id, creator, metadataPath) = currentDigitalMediaStore.getCollection(_id);
DigitalMediaCollection memory collection = DigitalMediaCollection({
id: id,
creator: creator,
metadataPath: metadataPath
});
return collection;
}
/**
* Retrieves a digital media object by id.
*/
function _getDigitalMedia(uint256 _id)
internal
view
managersInitialized
returns(DigitalMedia) {
uint256 id;
uint32 totalSupply;
uint32 printIndex;
uint256 collectionId;
address creator;
string memory metadataPath;
DigitalMediaStoreInterface _digitalMediaStore = _getDigitalMediaStore(_id);
(id, totalSupply, printIndex, collectionId, creator, metadataPath) = _digitalMediaStore.getDigitalMedia(_id);
DigitalMedia memory digitalMedia = DigitalMedia({
id: id,
creator: creator,
totalSupply: totalSupply,
printIndex: printIndex,
collectionId: collectionId,
metadataPath: metadataPath
});
return digitalMedia;
}
/**
* Increments the print index of a digital media object by some increment.
*/
function _incrementDigitalMediaPrintIndex(DigitalMedia _dm, uint32 _increment)
internal
managersInitialized {
DigitalMediaStoreInterface _digitalMediaStore = _getDigitalMediaStore(_dm.id);
_digitalMediaStore.incrementDigitalMediaPrintIndex(_dm.id, _increment);
}
// Check if the token operator is approved for the owner address
function isOperatorApprovedForCustodialAccount(
address _operator,
address _owner) internal view registryInitialized returns(bool) {
return creatorRegistryStore.isOperatorApprovedForCustodialAccount(
_operator, _owner);
}
}
// File: REMIX_FILE_SYNC/SingleCreatorControl.sol
pragma solidity 0.4.25;
/**
* A special control class that's used to help enforce that a DigitalMedia contract
* will service only a single creator's address. This is used when deploying a
* custom token contract owned and managed by a single creator.
*/
contract SingleCreatorControl {
// The single allowed creator for this digital media contract.
address public singleCreatorAddress;
// The single creator has changed.
event SingleCreatorChanged(
address indexed previousCreatorAddress,
address indexed newCreatorAddress);
/**
* Sets the single creator associated with this contract. This function
* can only ever be called once, and should ideally be called at the point
* of constructing the smart contract.
*/
function setSingleCreator(address _singleCreatorAddress) internal {
require(singleCreatorAddress == address(0), "Single creator address already set.");
singleCreatorAddress = _singleCreatorAddress;
}
/**
* Checks whether a given creator address matches the single creator address.
* Will always return true if a single creator address was never set.
*/
function isAllowedSingleCreator(address _creatorAddress) internal view returns (bool) {
require(_creatorAddress != address(0), "0x0 creator addresses are not allowed.");
return singleCreatorAddress == address(0) || singleCreatorAddress == _creatorAddress;
}
/**
* A publicly accessible function that allows the current single creator
* assigned to this contract to change to another address.
*/
function changeSingleCreator(address _newCreatorAddress) public {
require(_newCreatorAddress != address(0));
require(msg.sender == singleCreatorAddress, "Not approved to change single creator.");
singleCreatorAddress = _newCreatorAddress;
emit SingleCreatorChanged(singleCreatorAddress, _newCreatorAddress);
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol
pragma solidity ^0.4.21;
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId) public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.4.21;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol
pragma solidity ^0.4.21;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/AddressUtils.sol
pragma solidity ^0.4.21;
/**
* 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: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol
pragma solidity ^0.4.21;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existance of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for a the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) {
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
address owner = ownerOf(_tokenId);
return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender);
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* @dev The call is not executed if the target address is not a contract
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol
pragma solidity ^0.4.21;
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is ERC721, ERC721BasicToken {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping (address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
function ERC721Token(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() public view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() public view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* @dev Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) {
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* @dev Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* @dev Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
// File: REMIX_FILE_SYNC/ERC721Safe.sol
pragma solidity 0.4.25;
// We have to specify what version of compiler this code will compile with
contract ERC721Safe is ERC721Token {
bytes4 constant internal InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant internal InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256)'));
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
// File: REMIX_FILE_SYNC/Memory.sol
pragma solidity 0.4.25;
library Memory {
// Size of a word, in bytes.
uint internal constant WORD_SIZE = 32;
// Size of the header of a 'bytes' array.
uint internal constant BYTES_HEADER_SIZE = 32;
// Address of the free memory pointer.
uint internal constant FREE_MEM_PTR = 0x40;
// Compares the 'len' bytes starting at address 'addr' in memory with the 'len'
// bytes starting at 'addr2'.
// Returns 'true' if the bytes are the same, otherwise 'false'.
function equals(uint addr, uint addr2, uint len) internal pure returns (bool equal) {
assembly {
equal := eq(keccak256(addr, len), keccak256(addr2, len))
}
}
// Compares the 'len' bytes starting at address 'addr' in memory with the bytes stored in
// 'bts'. It is allowed to set 'len' to a lower value then 'bts.length', in which case only
// the first 'len' bytes will be compared.
// Requires that 'bts.length >= len'
function equals(uint addr, uint len, bytes memory bts) internal pure returns (bool equal) {
require(bts.length >= len);
uint addr2;
assembly {
addr2 := add(bts, /*BYTES_HEADER_SIZE*/32)
}
return equals(addr, addr2, len);
}
// Allocates 'numBytes' bytes in memory. This will prevent the Solidity compiler
// from using this area of memory. It will also initialize the area by setting
// each byte to '0'.
function allocate(uint numBytes) internal pure returns (uint addr) {
// Take the current value of the free memory pointer, and update.
assembly {
addr := mload(/*FREE_MEM_PTR*/0x40)
mstore(/*FREE_MEM_PTR*/0x40, add(addr, numBytes))
}
uint words = (numBytes + WORD_SIZE - 1) / WORD_SIZE;
for (uint i = 0; i < words; i++) {
assembly {
mstore(add(addr, mul(i, /*WORD_SIZE*/32)), 0)
}
}
}
// Copy 'len' bytes from memory address 'src', to address 'dest'.
// This function does not check the or destination, it only copies
// the bytes.
function copy(uint src, uint dest, uint len) internal pure {
// Copy word-length chunks while possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
dest += WORD_SIZE;
src += WORD_SIZE;
}
// Copy remaining bytes
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
// Returns a memory pointer to the provided bytes array.
function ptr(bytes memory bts) internal pure returns (uint addr) {
assembly {
addr := bts
}
}
// Returns a memory pointer to the data portion of the provided bytes array.
function dataPtr(bytes memory bts) internal pure returns (uint addr) {
assembly {
addr := add(bts, /*BYTES_HEADER_SIZE*/32)
}
}
// This function does the same as 'dataPtr(bytes memory)', but will also return the
// length of the provided bytes array.
function fromBytes(bytes memory bts) internal pure returns (uint addr, uint len) {
len = bts.length;
assembly {
addr := add(bts, /*BYTES_HEADER_SIZE*/32)
}
}
// Creates a 'bytes memory' variable from the memory address 'addr', with the
// length 'len'. The function will allocate new memory for the bytes array, and
// the 'len bytes starting at 'addr' will be copied into that new memory.
function toBytes(uint addr, uint len) internal pure returns (bytes memory bts) {
bts = new bytes(len);
uint btsptr;
assembly {
btsptr := add(bts, /*BYTES_HEADER_SIZE*/32)
}
copy(addr, btsptr, len);
}
// Get the word stored at memory address 'addr' as a 'uint'.
function toUint(uint addr) internal pure returns (uint n) {
assembly {
n := mload(addr)
}
}
// Get the word stored at memory address 'addr' as a 'bytes32'.
function toBytes32(uint addr) internal pure returns (bytes32 bts) {
assembly {
bts := mload(addr)
}
}
/*
// Get the byte stored at memory address 'addr' as a 'byte'.
function toByte(uint addr, uint8 index) internal pure returns (byte b) {
require(index < WORD_SIZE);
uint8 n;
assembly {
n := byte(index, mload(addr))
}
b = byte(n);
}
*/
}
// File: REMIX_FILE_SYNC/HelperUtils.sol
pragma solidity 0.4.25;
/**
* Internal helper functions
*/
contract HelperUtils {
// converts bytes32 to a string
// enable this when you use it. Saving gas for now
// function bytes32ToString(bytes32 x) private pure 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);
// }
/**
* Concatenates two strings
* @param _a string
* @param _b string
* @return string concatenation of two string
*/
function strConcat(string _a, string _b) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
string memory ab = new string(_ba.length + _bb.length);
bytes memory bab = bytes(ab);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
return string(bab);
}
}
// File: REMIX_FILE_SYNC/DigitalMediaToken.sol
pragma solidity 0.4.25;
/**
* The DigitalMediaToken contract. Fully implements the ERC721 contract
* from OpenZeppelin without any modifications to it.
*
* This contract allows for the creation of:
* 1. New Collections
* 2. New DigitalMedia objects
* 3. New DigitalMediaRelease objects
*
* The primary piece of logic is to ensure that an ERC721 token can
* have a supply and print edition that is enforced by this contract.
*/
contract DigitalMediaToken is DigitalMediaManager, ERC721Safe, HelperUtils, SingleCreatorControl {
event DigitalMediaReleaseCreateEvent(
uint256 id,
address owner,
uint32 printEdition,
string tokenURI,
uint256 digitalMediaId);
// Event fired when a new digital media is created
event DigitalMediaCreateEvent(
uint256 id,
address storeContractAddress,
address creator,
uint32 totalSupply,
uint32 printIndex,
uint256 collectionId,
string metadataPath);
// Event fired when a digital media's collection is
event DigitalMediaCollectionCreateEvent(
uint256 id,
address storeContractAddress,
address creator,
string metadataPath);
// Event fired when a digital media is burned
event DigitalMediaBurnEvent(
uint256 id,
address caller,
address storeContractAddress);
// Event fired when burning a token
event DigitalMediaReleaseBurnEvent(
uint256 tokenId,
address owner);
event UpdateDigitalMediaPrintIndexEvent(
uint256 digitalMediaId,
uint32 printEdition);
// Event fired when a creator assigns a new creator address.
event ChangedCreator(
address creator,
address newCreator);
struct DigitalMediaRelease {
// The unique edition number of this digital media release
uint32 printEdition;
// Reference ID to the digital media metadata
uint256 digitalMediaId;
}
// Maps internal ERC721 token ID to digital media release object.
mapping (uint256 => DigitalMediaRelease) public tokenIdToDigitalMediaRelease;
// Maps a creator address to a new creator address. Useful if a creator
// changes their address or the previous address gets compromised.
mapping (address => address) public approvedCreators;
// Token ID counter
uint256 internal tokenIdCounter = 0;
constructor (string _tokenName, string _tokenSymbol, uint256 _tokenIdStartingCounter)
public ERC721Token(_tokenName, _tokenSymbol) {
tokenIdCounter = _tokenIdStartingCounter;
}
/**
* Creates a new digital media object.
* @param _creator address the creator of this digital media
* @param _totalSupply uint32 the total supply a creation could have
* @param _collectionId uint256 the collectionId that it belongs to
* @param _metadataPath string the path to the ipfs metadata
* @return uint the new digital media id
*/
function _createDigitalMedia(
address _creator, uint32 _totalSupply, uint256 _collectionId, string _metadataPath)
internal
returns (uint) {
require(_validateCollection(_collectionId, _creator), "Creator for collection not approved.");
uint256 newDigitalMediaId = currentDigitalMediaStore.createDigitalMedia(
_creator,
0,
_totalSupply,
_collectionId,
_metadataPath);
emit DigitalMediaCreateEvent(
newDigitalMediaId,
address(currentDigitalMediaStore),
_creator,
_totalSupply,
0,
_collectionId,
_metadataPath);
return newDigitalMediaId;
}
/**
* Burns a token for a given tokenId and caller.
* @param _tokenId the id of the token to burn.
* @param _caller the address of the caller.
*/
function _burnToken(uint256 _tokenId, address _caller) internal {
address owner = ownerOf(_tokenId);
require(_caller == owner ||
getApproved(_tokenId) == _caller ||
isApprovedForAll(owner, _caller),
"Failed token burn. Caller is not approved.");
_burn(owner, _tokenId);
delete tokenIdToDigitalMediaRelease[_tokenId];
emit DigitalMediaReleaseBurnEvent(_tokenId, owner);
}
/**
* Burns a digital media. Once this function succeeds, this digital media
* will no longer be able to mint any more tokens. Existing tokens need to be
* burned individually though.
* @param _digitalMediaId the id of the digital media to burn
* @param _caller the address of the caller.
*/
function _burnDigitalMedia(uint256 _digitalMediaId, address _caller) internal {
DigitalMedia memory _digitalMedia = _getDigitalMedia(_digitalMediaId);
require(_checkApprovedCreator(_digitalMedia.creator, _caller) ||
isApprovedForAll(_digitalMedia.creator, _caller),
"Failed digital media burn. Caller not approved.");
uint32 increment = _digitalMedia.totalSupply - _digitalMedia.printIndex;
_incrementDigitalMediaPrintIndex(_digitalMedia, increment);
address _burnDigitalMediaStoreAddress = address(_getDigitalMediaStore(_digitalMedia.id));
emit DigitalMediaBurnEvent(
_digitalMediaId, _caller, _burnDigitalMediaStoreAddress);
}
/**
* Creates a new collection
* @param _creator address the creator of this collection
* @param _metadataPath string the path to the collection ipfs metadata
* @return uint the new collection id
*/
function _createCollection(
address _creator, string _metadataPath)
internal
returns (uint) {
uint256 newCollectionId = currentDigitalMediaStore.createCollection(
_creator,
_metadataPath);
emit DigitalMediaCollectionCreateEvent(
newCollectionId,
address(currentDigitalMediaStore),
_creator,
_metadataPath);
return newCollectionId;
}
/**
* Creates _count number of new digital media releases (i.e a token).
* Bumps up the print index by _count.
* @param _owner address the owner of the digital media object
* @param _digitalMediaId uint256 the digital media id
*/
function _createDigitalMediaReleases(
address _owner, uint256 _digitalMediaId, uint32 _count)
internal {
require(_count > 0, "Failed print edition. Creation count must be > 0.");
require(_count < 10000, "Cannot print more than 10K tokens at once");
DigitalMedia memory _digitalMedia = _getDigitalMedia(_digitalMediaId);
uint32 currentPrintIndex = _digitalMedia.printIndex;
require(_checkApprovedCreator(_digitalMedia.creator, _owner), "Creator not approved.");
require(isAllowedSingleCreator(_owner), "Creator must match single creator address.");
require(_count + currentPrintIndex <= _digitalMedia.totalSupply, "Total supply exceeded.");
string memory tokenURI = HelperUtils.strConcat("ipfs://ipfs/", _digitalMedia.metadataPath);
for (uint32 i=0; i < _count; i++) {
uint32 newPrintEdition = currentPrintIndex + 1 + i;
DigitalMediaRelease memory _digitalMediaRelease = DigitalMediaRelease({
printEdition: newPrintEdition,
digitalMediaId: _digitalMediaId
});
uint256 newDigitalMediaReleaseId = _getNextTokenId();
tokenIdToDigitalMediaRelease[newDigitalMediaReleaseId] = _digitalMediaRelease;
emit DigitalMediaReleaseCreateEvent(
newDigitalMediaReleaseId,
_owner,
newPrintEdition,
tokenURI,
_digitalMediaId
);
// This will assign ownership and also emit the Transfer event as per ERC721
_mint(_owner, newDigitalMediaReleaseId);
_setTokenURI(newDigitalMediaReleaseId, tokenURI);
tokenIdCounter = tokenIdCounter.add(1);
}
_incrementDigitalMediaPrintIndex(_digitalMedia, _count);
emit UpdateDigitalMediaPrintIndexEvent(_digitalMediaId, currentPrintIndex + _count);
}
/**
* Checks that a given caller is an approved creator and is allowed to mint or burn
* tokens. If the creator was changed it will check against the updated creator.
* @param _caller the calling address
* @return bool allowed or not
*/
function _checkApprovedCreator(address _creator, address _caller)
internal
view
returns (bool) {
address approvedCreator = approvedCreators[_creator];
if (approvedCreator != address(0)) {
return approvedCreator == _caller;
} else {
return _creator == _caller;
}
}
/**
* Validates the an address is allowed to create a digital media on a
* given collection. Collections are tied to addresses.
*/
function _validateCollection(uint256 _collectionId, address _address)
private
view
returns (bool) {
if (_collectionId == 0 ) {
return true;
}
DigitalMediaCollection memory collection = _getCollection(_collectionId);
return _checkApprovedCreator(collection.creator, _address);
}
/**
* Generates a new token id.
*/
function _getNextTokenId() private view returns (uint256) {
return tokenIdCounter.add(1);
}
/**
* Changes the creator that is approved to printing new tokens and creations.
* Either the _caller must be the _creator or the _caller must be the existing
* approvedCreator.
* @param _caller the address of the caller
* @param _creator the address of the current creator
* @param _newCreator the address of the new approved creator
*/
function _changeCreator(address _caller, address _creator, address _newCreator) internal {
address approvedCreator = approvedCreators[_creator];
require(_caller != address(0) && _creator != address(0), "Creator must be valid non 0x0 address.");
require(_caller == _creator || _caller == approvedCreator, "Unauthorized caller.");
if (approvedCreator == address(0)) {
approvedCreators[_caller] = _newCreator;
} else {
require(_caller == approvedCreator, "Unauthorized caller.");
approvedCreators[_creator] = _newCreator;
}
emit ChangedCreator(_creator, _newCreator);
}
/**
* Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
}
// File: REMIX_FILE_SYNC/OBOControl.sol
pragma solidity 0.4.25;
contract OBOControl is Pausable {
// List of approved on behalf of users.
mapping (address => bool) public approvedOBOs;
/**
* Add a new approved on behalf of user address.
*/
function addApprovedOBO(address _oboAddress) external onlyOwner {
approvedOBOs[_oboAddress] = true;
}
/**
* Removes an approved on bhealf of user address.
*/
function removeApprovedOBO(address _oboAddress) external onlyOwner {
delete approvedOBOs[_oboAddress];
}
/**
* @dev Modifier to make the obo calls only callable by approved addressess
*/
modifier isApprovedOBO() {
require(approvedOBOs[msg.sender] == true);
_;
}
}
// File: REMIX_FILE_SYNC/WithdrawFundsControl.sol
pragma solidity 0.4.25;
contract WithdrawFundsControl is Pausable {
// List of approved on withdraw addresses
mapping (address => uint256) public approvedWithdrawAddresses;
// Full day wait period before an approved withdraw address becomes active
uint256 constant internal withdrawApprovalWaitPeriod = 60 * 60 * 24;
event WithdrawAddressAdded(address withdrawAddress);
event WithdrawAddressRemoved(address widthdrawAddress);
/**
* Add a new approved on behalf of user address.
*/
function addApprovedWithdrawAddress(address _withdrawAddress) external onlyOwner {
approvedWithdrawAddresses[_withdrawAddress] = now;
emit WithdrawAddressAdded(_withdrawAddress);
}
/**
* Removes an approved on bhealf of user address.
*/
function removeApprovedWithdrawAddress(address _withdrawAddress) external onlyOwner {
delete approvedWithdrawAddresses[_withdrawAddress];
emit WithdrawAddressRemoved(_withdrawAddress);
}
/**
* Checks that a given withdraw address ia approved and is past it's required
* wait time.
*/
function isApprovedWithdrawAddress(address _withdrawAddress) internal view returns (bool) {
uint256 approvalTime = approvedWithdrawAddresses[_withdrawAddress];
require (approvalTime > 0);
return now - approvalTime > withdrawApprovalWaitPeriod;
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Holder.sol
pragma solidity ^0.4.21;
contract ERC721Holder is ERC721Receiver {
function onERC721Received(address, uint256, bytes) public returns(bytes4) {
return ERC721_RECEIVED;
}
}
// File: REMIX_FILE_SYNC/DigitalMediaSaleBase.sol
pragma solidity 0.4.25;
/**
* Base class that manages the underlying functions of a Digital Media Sale,
* most importantly the escrow of digital tokens.
*
* Manages ensuring that only approved addresses interact with this contract.
*
*/
contract DigitalMediaSaleBase is ERC721Holder, Pausable, OBOControl, WithdrawFundsControl {
using SafeMath for uint256;
// Mapping of token contract address to bool indicated approval.
mapping (address => bool) public approvedTokenContracts;
/**
* Adds a new token contract address to be approved to be called.
*/
function addApprovedTokenContract(address _tokenContractAddress)
public onlyOwner {
approvedTokenContracts[_tokenContractAddress] = true;
}
/**
* Remove an approved token contract address from the list of approved addresses.
*/
function removeApprovedTokenContract(address _tokenContractAddress)
public onlyOwner {
delete approvedTokenContracts[_tokenContractAddress];
}
/**
* Checks that a particular token contract address is a valid address.
*/
function _isValidTokenContract(address _tokenContractAddress)
internal view returns (bool) {
return approvedTokenContracts[_tokenContractAddress];
}
/**
* Returns an ERC721 instance of a token contract address. Throws otherwise.
* Only valid and approved token contracts are allowed to be interacted with.
*/
function _getTokenContract(address _tokenContractAddress) internal view returns (ERC721Safe) {
require(_isValidTokenContract(_tokenContractAddress));
return ERC721Safe(_tokenContractAddress);
}
/**
* Checks with the ERC-721 token contract that the _claimant actually owns the token.
*/
function _owns(address _claimant, uint256 _tokenId, address _tokenContractAddress) internal view returns (bool) {
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
return (tokenContract.ownerOf(_tokenId) == _claimant);
}
/**
* Checks with the ERC-721 token contract the owner of the a token
*/
function _ownerOf(uint256 _tokenId, address _tokenContractAddress) internal view returns (address) {
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
return tokenContract.ownerOf(_tokenId);
}
/**
* Checks to ensure that the token owner has approved the escrow contract
*/
function _approvedForEscrow(address _seller, uint256 _tokenId, address _tokenContractAddress) internal view returns (bool) {
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
return (tokenContract.isApprovedForAll(_seller, this) ||
tokenContract.getApproved(_tokenId) == address(this));
}
/**
* Escrows an ERC-721 token from the seller to this contract. Assumes that the escrow contract
* is already approved to make the transfer, otherwise it will fail.
*/
function _escrow(address _seller, uint256 _tokenId, address _tokenContractAddress) internal {
// it will throw if transfer fails
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
tokenContract.safeTransferFrom(_seller, this, _tokenId);
}
/**
* Transfer an ERC-721 token from escrow to the buyer. This is to be called after a purchase is
* completed.
*/
function _transfer(address _receiver, uint256 _tokenId, address _tokenContractAddress) internal {
// it will throw if transfer fails
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
tokenContract.safeTransferFrom(this, _receiver, _tokenId);
}
/**
* Method to check whether this is an escrow contract
*/
function isEscrowContract() public pure returns(bool) {
return true;
}
/**
* Withdraws all the funds to a specified non-zero address
*/
function withdrawFunds(address _withdrawAddress) public onlyOwner {
require(isApprovedWithdrawAddress(_withdrawAddress));
_withdrawAddress.transfer(address(this).balance);
}
}
// File: REMIX_FILE_SYNC/DigitalMediaCore.sol
pragma solidity 0.4.25;
/**
* This is the main driver contract that is used to control and run the service. Funds
* are managed through this function, underlying contracts are also updated through
* this contract.
*
* This class also exposes a set of creation methods that are allowed to be created
* by an approved token creator, on behalf of a particular address. This is meant
* to simply the creation flow for MakersToken users that aren't familiar with
* the blockchain. The ERC721 tokens that are created are still fully compliant,
* although it is possible for a malicious token creator to mint unwanted tokens
* on behalf of a creator. Worst case, the creator can burn those tokens.
*/
contract DigitalMediaCore is DigitalMediaToken {
using SafeMath for uint32;
// List of approved token creators (on behalf of the owner)
mapping (address => bool) public approvedTokenCreators;
// Mapping from owner to operator accounts.
mapping (address => mapping (address => bool)) internal oboOperatorApprovals;
// Mapping of all disabled OBO operators.
mapping (address => bool) public disabledOboOperators;
// OboApproveAll Event
event OboApprovalForAll(
address _owner,
address _operator,
bool _approved);
// Fired when disbaling obo capability.
event OboDisabledForAll(address _operator);
constructor (
string _tokenName,
string _tokenSymbol,
uint256 _tokenIdStartingCounter,
address _dmsAddress,
address _crsAddress)
public DigitalMediaToken(
_tokenName,
_tokenSymbol,
_tokenIdStartingCounter) {
paused = true;
setDigitalMediaStoreAddress(_dmsAddress);
setCreatorRegistryStore(_crsAddress);
}
/**
* Retrieves a Digital Media object.
*/
function getDigitalMedia(uint256 _id)
external
view
returns (
uint256 id,
uint32 totalSupply,
uint32 printIndex,
uint256 collectionId,
address creator,
string metadataPath) {
DigitalMedia memory digitalMedia = _getDigitalMedia(_id);
require(digitalMedia.creator != address(0), "DigitalMedia not found.");
id = _id;
totalSupply = digitalMedia.totalSupply;
printIndex = digitalMedia.printIndex;
collectionId = digitalMedia.collectionId;
creator = digitalMedia.creator;
metadataPath = digitalMedia.metadataPath;
}
/**
* Retrieves a collection.
*/
function getCollection(uint256 _id)
external
view
returns (
uint256 id,
address creator,
string metadataPath) {
DigitalMediaCollection memory digitalMediaCollection = _getCollection(_id);
require(digitalMediaCollection.creator != address(0), "Collection not found.");
id = _id;
creator = digitalMediaCollection.creator;
metadataPath = digitalMediaCollection.metadataPath;
}
/**
* Retrieves a Digital Media Release (i.e a token)
*/
function getDigitalMediaRelease(uint256 _id)
external
view
returns (
uint256 id,
uint32 printEdition,
uint256 digitalMediaId) {
require(exists(_id));
DigitalMediaRelease storage digitalMediaRelease = tokenIdToDigitalMediaRelease[_id];
id = _id;
printEdition = digitalMediaRelease.printEdition;
digitalMediaId = digitalMediaRelease.digitalMediaId;
}
/**
* Creates a new collection.
*
* No creations of any kind are allowed when the contract is paused.
*/
function createCollection(string _metadataPath)
external
whenNotPaused {
_createCollection(msg.sender, _metadataPath);
}
/**
* Creates a new digital media object.
*/
function createDigitalMedia(uint32 _totalSupply, uint256 _collectionId, string _metadataPath)
external
whenNotPaused {
_createDigitalMedia(msg.sender, _totalSupply, _collectionId, _metadataPath);
}
/**
* Creates a new digital media object and mints it's first digital media release token.
*
* No creations of any kind are allowed when the contract is paused.
*/
function createDigitalMediaAndReleases(
uint32 _totalSupply,
uint256 _collectionId,
string _metadataPath,
uint32 _numReleases)
external
whenNotPaused {
uint256 digitalMediaId = _createDigitalMedia(msg.sender, _totalSupply, _collectionId, _metadataPath);
_createDigitalMediaReleases(msg.sender, digitalMediaId, _numReleases);
}
/**
* Creates a new collection, a new digital media object within it and mints a new
* digital media release token.
*
* No creations of any kind are allowed when the contract is paused.
*/
function createDigitalMediaAndReleasesInNewCollection(
uint32 _totalSupply,
string _digitalMediaMetadataPath,
string _collectionMetadataPath,
uint32 _numReleases)
external
whenNotPaused {
uint256 collectionId = _createCollection(msg.sender, _collectionMetadataPath);
uint256 digitalMediaId = _createDigitalMedia(msg.sender, _totalSupply, collectionId, _digitalMediaMetadataPath);
_createDigitalMediaReleases(msg.sender, digitalMediaId, _numReleases);
}
/**
* Creates a new digital media release (token) for a given digital media id.
*
* No creations of any kind are allowed when the contract is paused.
*/
function createDigitalMediaReleases(uint256 _digitalMediaId, uint32 _numReleases)
external
whenNotPaused {
_createDigitalMediaReleases(msg.sender, _digitalMediaId, _numReleases);
}
/**
* Deletes a token / digital media release. Doesn't modify the current print index
* and total to be printed. Although dangerous, the owner of a token should always
* be able to burn a token they own.
*
* Only the owner of the token or accounts approved by the owner can burn this token.
*/
function burnToken(uint256 _tokenId) external {
_burnToken(_tokenId, msg.sender);
}
/* Support ERC721 burn method */
function burn(uint256 tokenId) public {
_burnToken(tokenId, msg.sender);
}
/**
* Ends the production run of a digital media. Afterwards no more tokens
* will be allowed to be printed for this digital media. Used when a creator
* makes a mistake and wishes to burn and recreate their digital media.
*
* When a contract is paused we do not allow new tokens to be created,
* so stopping the production of a token doesn't have much purpose.
*/
function burnDigitalMedia(uint256 _digitalMediaId) external whenNotPaused {
_burnDigitalMedia(_digitalMediaId, msg.sender);
}
/**
* Resets the approval rights for a given tokenId.
*/
function resetApproval(uint256 _tokenId) external {
clearApproval(msg.sender, _tokenId);
}
/**
* Changes the creator for the current sender, in the event we
* need to be able to mint new tokens from an existing digital media
* print production. When changing creator, the old creator will
* no longer be able to mint tokens.
*
* A creator may need to be changed:
* 1. If we want to allow a creator to take control over their token minting (i.e go decentralized)
* 2. If we want to re-issue private keys due to a compromise. For this reason, we can call this function
* when the contract is paused.
* @param _creator the creator address
* @param _newCreator the new creator address
*/
function changeCreator(address _creator, address _newCreator) external {
_changeCreator(msg.sender, _creator, _newCreator);
}
/**********************************************************************/
/**Calls that are allowed to be called by approved creator addresses **/
/**********************************************************************/
/**
* Add a new approved token creator.
*
* Only the owner of this contract can update approved Obo accounts.
*/
function addApprovedTokenCreator(address _creatorAddress) external onlyOwner {
require(disabledOboOperators[_creatorAddress] != true, "Address disabled.");
approvedTokenCreators[_creatorAddress] = true;
}
/**
* Removes an approved token creator.
*
* Only the owner of this contract can update approved Obo accounts.
*/
function removeApprovedTokenCreator(address _creatorAddress) external onlyOwner {
delete approvedTokenCreators[_creatorAddress];
}
/**
* @dev Modifier to make the approved creation calls only callable by approved token creators
*/
modifier isApprovedCreator() {
require(
(approvedTokenCreators[msg.sender] == true &&
disabledOboOperators[msg.sender] != true),
"Unapproved OBO address.");
_;
}
/**
* Only the owner address can set a special obo approval list.
* When issuing OBO management accounts, we should give approvals through
* this method only so that we can very easily reset it's approval in
* the event of a disaster scenario.
*
* Only the owner themselves is allowed to give OboApproveAll access.
*/
function setOboApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender, "Approval address is same as approver.");
require(approvedTokenCreators[_to], "Unrecognized OBO address.");
require(disabledOboOperators[_to] != true, "Approval address is disabled.");
oboOperatorApprovals[msg.sender][_to] = _approved;
emit OboApprovalForAll(msg.sender, _to, _approved);
}
/**
* Only called in a disaster scenario if the account has been compromised.
* There's no turning back from this and the oboAddress will no longer be
* able to be given approval rights or perform obo functions.
*
* Only the owner of this contract is allowed to disable an Obo address.
*
*/
function disableOboAddress(address _oboAddress) public onlyOwner {
require(approvedTokenCreators[_oboAddress], "Unrecognized OBO address.");
disabledOboOperators[_oboAddress] = true;
delete approvedTokenCreators[_oboAddress];
emit OboDisabledForAll(_oboAddress);
}
/**
* Override the isApprovalForAll to check for a special oboApproval list. Reason for this
* is that we can can easily remove obo operators if they every become compromised.
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
if (disabledOboOperators[_operator] == true) {
return false;
} else if (isOperatorApprovedForCustodialAccount(_operator, _owner) == true) {
return true;
} else if (oboOperatorApprovals[_owner][_operator]) {
return true;
} else {
return super.isApprovedForAll(_owner, _operator);
}
}
/**
* Creates a new digital media object and mints it's digital media release tokens.
* Called on behalf of the _owner. Pass count to mint `n` number of tokens.
*
* Only approved creators are allowed to create Obo.
*
* No creations of any kind are allowed when the contract is paused.
*/
function oboCreateDigitalMediaAndReleases(
address _owner,
uint32 _totalSupply,
uint256 _collectionId,
string _metadataPath,
uint32 _numReleases)
external
whenNotPaused
isApprovedCreator {
uint256 digitalMediaId = _createDigitalMedia(_owner, _totalSupply, _collectionId, _metadataPath);
_createDigitalMediaReleases(_owner, digitalMediaId, _numReleases);
}
/**
* Creates a new collection, a new digital media object within it and mints a new
* digital media release token.
* Called on behalf of the _owner.
*
* Only approved creators are allowed to create Obo.
*
* No creations of any kind are allowed when the contract is paused.
*/
function oboCreateDigitalMediaAndReleasesInNewCollection(
address _owner,
uint32 _totalSupply,
string _digitalMediaMetadataPath,
string _collectionMetadataPath,
uint32 _numReleases)
external
whenNotPaused
isApprovedCreator {
uint256 collectionId = _createCollection(_owner, _collectionMetadataPath);
uint256 digitalMediaId = _createDigitalMedia(_owner, _totalSupply, collectionId, _digitalMediaMetadataPath);
_createDigitalMediaReleases(_owner, digitalMediaId, _numReleases);
}
/**
* Creates multiple digital media releases (tokens) for a given digital media id.
* Called on behalf of the _owner.
*
* Only approved creators are allowed to create Obo.
*
* No creations of any kind are allowed when the contract is paused.
*/
function oboCreateDigitalMediaReleases(
address _owner,
uint256 _digitalMediaId,
uint32 _numReleases)
external
whenNotPaused
isApprovedCreator {
_createDigitalMediaReleases(_owner, _digitalMediaId, _numReleases);
}
} | * Internal helper functions/ converts bytes32 to a string enable this when you use it. Saving gas for now function bytes32ToString(bytes32 x) private pure 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); } | contract HelperUtils {
}
function strConcat(string _a, string _b) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
string memory ab = new string(_ba.length + _bb.length);
bytes memory bab = bytes(ab);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
return string(bab);
}
}
| 890,369 | [
1,
3061,
4222,
4186,
19,
7759,
1731,
1578,
358,
279,
533,
4237,
333,
1347,
1846,
999,
518,
18,
348,
5339,
16189,
364,
2037,
445,
1731,
1578,
5808,
12,
3890,
1578,
619,
13,
3238,
16618,
1135,
261,
1080,
13,
288,
377,
1731,
3778,
1731,
780,
273,
394,
1731,
12,
1578,
1769,
377,
2254,
1149,
1380,
273,
374,
31,
377,
364,
261,
11890,
525,
273,
374,
31,
525,
411,
3847,
31,
525,
27245,
288,
540,
1160,
1149,
273,
1160,
12,
3890,
1578,
12,
11890,
12,
92,
13,
225,
576,
225,
261,
28,
225,
525,
3719,
1769,
540,
309,
261,
3001,
480,
374,
13,
288,
2398,
1731,
780,
63,
3001,
1380,
65,
273,
1149,
31,
2398,
1149,
1380,
9904,
31,
540,
289,
377,
289,
377,
1731,
3778,
1731,
780,
14795,
2937,
273,
394,
1731,
12,
3001,
1380,
1769,
377,
364,
261,
78,
273,
374,
31,
525,
411,
1149,
1380,
31,
525,
27245,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
9705,
1989,
288,
203,
203,
203,
97,
203,
203,
565,
445,
609,
15113,
12,
1080,
389,
69,
16,
533,
389,
70,
13,
2713,
16618,
1135,
261,
1080,
13,
288,
203,
3639,
1731,
3778,
389,
12124,
273,
1731,
24899,
69,
1769,
203,
3639,
1731,
3778,
389,
9897,
273,
1731,
24899,
70,
1769,
203,
3639,
533,
3778,
1223,
273,
394,
533,
24899,
12124,
18,
2469,
397,
389,
9897,
18,
2469,
1769,
203,
3639,
1731,
3778,
324,
378,
273,
1731,
12,
378,
1769,
203,
3639,
2254,
417,
273,
374,
31,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
389,
12124,
18,
2469,
31,
277,
27245,
324,
378,
63,
79,
9904,
65,
273,
389,
12124,
63,
77,
15533,
203,
3639,
364,
261,
77,
273,
374,
31,
277,
411,
389,
9897,
18,
2469,
31,
277,
27245,
324,
378,
63,
79,
9904,
65,
273,
389,
9897,
63,
77,
15533,
203,
3639,
327,
533,
12,
70,
378,
1769,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xa52c0Bb1b802e9d6A483072d56fd22B58B964455/sources/contracts/mixins/nftDropMarket/NFTDropMarketCore.sol | @notice Requires the given NFT contract can mint at least 1 more NFT. | modifier notSoldOut(address nftContract) {
if (INFTLazyMintedCollectionMintCountTo(nftContract).numberOfTokensAvailableToMint() == 0) {
revert NFTDropMarketCore_Must_Have_Available_Supply();
}
_;
}
| 2,625,047 | [
1,
21671,
326,
864,
423,
4464,
6835,
848,
312,
474,
622,
4520,
404,
1898,
423,
4464,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
9606,
486,
55,
1673,
1182,
12,
2867,
290,
1222,
8924,
13,
288,
203,
565,
309,
261,
706,
4464,
14443,
49,
474,
329,
2532,
49,
474,
1380,
774,
12,
82,
1222,
8924,
2934,
2696,
951,
5157,
5268,
774,
49,
474,
1435,
422,
374,
13,
288,
203,
1377,
15226,
423,
4464,
7544,
3882,
278,
4670,
67,
10136,
67,
17944,
67,
5268,
67,
3088,
1283,
5621,
203,
565,
289,
203,
565,
389,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
pragma experimental ABIEncoderV2;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../node_modules/@nomiclabs/buidler/console.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
struct Profile {
string name;
address wallet;
bool isAirline;
bool acceptedByOtherAirlines;
bool hasPayedFund;
}
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
mapping(address => Profile) airlines; // Mapping for storing airlines
address[] registeredAirlines = new address[](0);
address[] allAirlines = new address[](0);
mapping(address => address[]) multipartyConsensusNewAirline; // Mapping from a potential airline to airlines that gave consensus
uint256 public constant MIN_FUND = 10 ether; //minimum fund required to participate in contract
mapping(address => Passenger) passengers;
mapping(bytes32 => address[]) passengersPerFlight;
struct Flight {
string name;
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
struct Passenger {
address wallet;
mapping(bytes32 => uint256) purchasedInsurance;
uint256 credits;
}
mapping(bytes32 => Flight) private flights;
bytes32[] private flightList;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
)
public
{
contractOwner = msg.sender;
airlines[msg.sender] = Profile({
name : "First Airline inc.",
isAirline : true,
wallet : msg.sender,
acceptedByOtherAirlines : true,
hasPayedFund : false
});
registeredAirlines.push(msg.sender);
allAirlines.push(msg.sender);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_;
// All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier requireIsAirline()
{
// Modify to call data contract's status
require(airlines[msg.sender].isAirline, "Caller is no registered airline");
_;
// All modifiers require an "_" which indicates where the function body will be added
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Check if an airline is registered
*
* @return A bool that indicates if the airline is registered
*/
function isAirline
(
address wallet
)
external
view
returns (bool)
{
return airlines[wallet].isAirline;
}
function getAirline
(
address wallet
)
external
view
returns (Profile memory)
{
return airlines[wallet];
}
function getAllAirline() external view returns (Profile[] memory)
{
uint256 index = 0;
Profile[] memory airlineProfile = new Profile[](allAirlines.length);
while (index < allAirlines.length) {
address key = allAirlines[index];
airlineProfile[index] = airlines[key];
index = index + 1;
}
return airlineProfile;
}
function getAllFlights() external view returns (Flight[] memory)
{
uint256 index = 0;
Flight[] memory allFlights = new Flight[](flightList.length);
while (index < flightList.length) {
bytes32 key = flightList[index];
allFlights[index] = flights[key];
index = index + 1;
}
return allFlights;
}
function getPassengerInsurance(address wallet, bytes32 key) external view returns (uint256 amount)
{
return passengers[wallet].purchasedInsurance[key];
}
function getPassengerCredit(address wallet) external view returns (uint256 amount)
{
return passengers[wallet].credits;
}
function getNumberOfRegisteredAirlines
(
)
external
view
returns (uint256)
{
return registeredAirlines.length;
}
function getConsendingAirlines
(
address wallet
)
external
view
returns (address[] memory)
{
return multipartyConsensusNewAirline[wallet];
}
function resetConsendingAirlines(address newAirline) external {
multipartyConsensusNewAirline[newAirline] = new address[](0);
}
function addConsendingAirlines(address newAirline, address existingAirline) external {
multipartyConsensusNewAirline[newAirline].push(existingAirline);
}
function updateAirlineAcceptedByOtherAirlines(address wallet, bool hasConsensus)
external returns (bool) {
airlines[wallet].acceptedByOtherAirlines = hasConsensus;
airlines[wallet].wallet = wallet;
return checkIfQualifiesForAirline(wallet);
}
function updateAirlineNameAndHasPayedFund(address wallet, string name, bool hasPayedFund)
external {
airlines[wallet].name = name;
airlines[wallet].wallet = wallet;
airlines[wallet].hasPayedFund = true;
checkIfQualifiesForAirline(wallet);
}
function updateFlightStatus(string flightName, uint256 flightTimestamp, address airline, uint8 status)
external {
bytes32 key = keccak256(abi.encodePacked(airline, flightName, flightTimestamp));
require(flights[key].isRegistered, "Flight has to be registered");
flights[key].statusCode = status;
}
function isFlightRegisterd(bytes32 key) external view returns (bool){
return flights[key].isRegistered;
}
function updateFlight(string flightName, uint256 flightTimestamp, address airline)
external returns (bytes32) {
bytes32 key = keccak256(abi.encodePacked(airline, flightName, flightTimestamp));
require(!flights[key].isRegistered, "Flight already registered");
flights[key] = Flight({
name : flightName,
isRegistered : true,
statusCode : 0,
updatedTimestamp : flightTimestamp,
airline : airline
});
flightList.push(key);
return key;
}
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns (bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
function checkIfQualifiesForAirline(address wallet) internal returns (bool){
bool doesListContainElement = false;
for (uint i = 0; i < allAirlines.length; i++) {
if (wallet == allAirlines[i]) {
doesListContainElement = true;
}
}
if (!doesListContainElement) {
allAirlines.push(wallet);
}
if (airlines[wallet].acceptedByOtherAirlines && airlines[wallet].hasPayedFund) {
airlines[wallet].isAirline = true;
registeredAirlines.push(wallet);
return true;
}
return false;
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(address airline, string flight, uint256 timestamp)
external
payable
{
bytes32 key = keccak256(abi.encodePacked(airline, flight, timestamp));
address wallet = msg.sender;
if (passengers[wallet].wallet == address(0)) {
passengers[wallet] = Passenger({
wallet : wallet,
credits : 0
});
}
if (passengers[wallet].purchasedInsurance[key] == 0) {
passengers[wallet].purchasedInsurance[key] = msg.value;
passengersPerFlight[key].push(wallet);
} else {
require(false, "Insurance already bought for flight");
}
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
address airline, string flight, uint256 timestamp,
uint multiplier
)
external
{
bytes32 key = keccak256(abi.encodePacked(airline, flight, timestamp));
address[] passengerListFlight = passengersPerFlight[key];
for (uint i = 0; i < passengerListFlight.length; i++) {
address insuree = passengerListFlight[i];
uint256 payoutAmound = passengers[insuree].purchasedInsurance[key].mul(3).div(2);
passengers[insuree].purchasedInsurance[key] = 0;
passengers[insuree].credits = passengers[insuree].credits + payoutAmound;
}
delete passengersPerFlight[key];
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(
)
external
{
uint256 amount = passengers[msg.sender].credits;
passengers[msg.sender].credits = 0;
msg.sender.transfer(amount);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund
(
)
public
payable
{
}
function getFlightKey
(
address airline,
string flight,
uint256 timestamp
)
pure
external
returns (bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
function authorizeCaller(address caller) external pure {
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
fund();
}
}
| * @dev Fallback function for funding smart contract./ | function()
external
payable
{
fund();
}
| 5,445,624 | [
1,
12355,
445,
364,
22058,
13706,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1435,
203,
565,
3903,
203,
565,
8843,
429,
203,
565,
288,
203,
3639,
284,
1074,
5621,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library 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/SafeMath96.sol
pragma solidity 0.6.12;
/**
* @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 SafeMath96 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint96 a, uint256 b) internal pure returns (uint96) {
require(uint256(uint96(b)) == b, "SafeMath: addition overflow");
uint96 c = a + uint96(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(uint96 a, uint256 b) internal pure returns (uint96) {
require(uint256(uint96(b)) == b, "SafeMath: subtraction overflow");
return sub(a, uint96(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(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
uint96 c = a - b;
return c;
}
}
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/spec_interfaces/ICommittee.sol
pragma solidity 0.6.12;
/// @title Committee contract interface
interface ICommittee {
event CommitteeChange(address indexed addr, uint256 weight, bool certification, bool inCommittee);
event CommitteeSnapshot(address[] addrs, uint256[] weights, bool[] certification);
// No external functions
/*
* External functions
*/
/// Notifies a weight change of a member
/// @dev Called only by: Elections contract
/// @param addr is the committee member address
/// @param weight is the updated weight of the committee member
function memberWeightChange(address addr, uint256 weight) external /* onlyElectionsContract onlyWhenActive */;
/// Notifies a change in the certification of a member
/// @dev Called only by: Elections contract
/// @param addr is the committee member address
/// @param isCertified is the updated certification state of the member
function memberCertificationChange(address addr, bool isCertified) external /* onlyElectionsContract onlyWhenActive */;
/// Notifies a member removal for example due to voteOut or voteUnready
/// @dev Called only by: Elections contract
/// @param memberRemoved is the removed committee member address
/// @return memberRemoved indicates whether the member was removed from the committee
/// @return removedMemberWeight indicates the removed member weight
/// @return removedMemberCertified indicates whether the member was in the certified committee
function removeMember(address addr) external returns (bool memberRemoved, uint removedMemberWeight, bool removedMemberCertified)/* onlyElectionContract */;
/// Notifies a new member applicable for committee (due to registration, unbanning, certification change)
/// The new member will be added only if it is qualified to join the committee
/// @dev Called only by: Elections contract
/// @param addr is the added committee member address
/// @param weight is the added member weight
/// @param isCertified is the added member certification state
/// @return memberAdded bool indicates whether the member was added
function addMember(address addr, uint256 weight, bool isCertified) external returns (bool memberAdded) /* onlyElectionsContract */;
/// Checks if addMember() would add a the member to the committee (qualified to join)
/// @param addr is the candidate committee member address
/// @param weight is the candidate committee member weight
/// @return wouldAddMember bool indicates whether the member will be added
function checkAddMember(address addr, uint256 weight) external view returns (bool wouldAddMember);
/// Returns the committee members and their weights
/// @return addrs is the committee members list
/// @return weights is an array of uint, indicating committee members list weight
/// @return certification is an array of bool, indicating the committee members certification status
function getCommittee() external view returns (address[] memory addrs, uint256[] memory weights, bool[] memory certification);
/// Returns the currently appointed committee data
/// @return generalCommitteeSize is the number of members in the committee
/// @return certifiedCommitteeSize is the number of certified members in the committee
/// @return totalWeight is the total effective stake (weight) of the committee
function getCommitteeStats() external view returns (uint generalCommitteeSize, uint certifiedCommitteeSize, uint totalWeight);
/// Returns a committee member data
/// @param addr is the committee member address
/// @return inCommittee indicates whether the queried address is a member in the committee
/// @return weight is the committee member weight
/// @return isCertified indicates whether the committee member is certified
/// @return totalCommitteeWeight is the total weight of the committee.
function getMemberInfo(address addr) external view returns (bool inCommittee, uint weight, bool isCertified, uint totalCommitteeWeight);
/// Emits a CommitteeSnapshot events with current committee info
/// @dev a CommitteeSnapshot is useful on contract migration or to remove the need to track past events.
function emitCommitteeSnapshot() external;
/*
* Governance functions
*/
event MaxCommitteeSizeChanged(uint8 newValue, uint8 oldValue);
/// Sets the maximum number of committee members
/// @dev governance function called only by the functional manager
/// @dev when reducing the number of members, the bottom ones are removed from the committee
/// @param _maxCommitteeSize is the maximum number of committee members
function setMaxCommitteeSize(uint8 _maxCommitteeSize) external /* onlyFunctionalManager */;
/// Returns the maximum number of committee members
/// @return maxCommitteeSize is the maximum number of committee members
function getMaxCommitteeSize() external view returns (uint8);
/// Imports the committee members from a previous committee contract during migration
/// @dev initialization function called only by the initializationManager
/// @dev does not update the reward contract to avoid incorrect notifications
/// @param previousCommitteeContract is the address of the previous committee contract
function importMembers(ICommittee previousCommitteeContract) external /* onlyInitializationAdmin */;
}
// File: contracts/spec_interfaces/IProtocolWallet.sol
pragma solidity 0.6.12;
/// @title Protocol Wallet interface
interface IProtocolWallet {
event FundsAddedToPool(uint256 added, uint256 total);
/*
* External functions
*/
/// Returns the address of the underlying staked token
/// @return balance is the wallet balance
function getBalance() external view returns (uint256 balance);
/// Transfers the given amount of orbs tokens form the sender to this contract and updates the pool
/// @dev assumes the caller approved the amount prior to calling
/// @param amount is the amount to add to the wallet
function topUp(uint256 amount) external;
/// Withdraws from pool to the client address, limited by the pool's MaxRate.
/// @dev may only be called by the wallet client
/// @dev no more than MaxRate x time period since the last withdraw may be withdrawn
/// @dev allocation that wasn't withdrawn can not be withdrawn in the next call
/// @param amount is the amount to withdraw
function withdraw(uint256 amount) external; /* onlyClient */
/*
* Governance functions
*/
event ClientSet(address client);
event MaxAnnualRateSet(uint256 maxAnnualRate);
event EmergencyWithdrawal(address addr, address token);
event OutstandingTokensReset(uint256 startTime);
/// Sets a new annual withdraw rate for the pool
/// @dev governance function called only by the migration owner
/// @dev the rate for a duration is duration x annualRate / 1 year
/// @param _annualRate is the maximum annual rate that can be withdrawn
function setMaxAnnualRate(uint256 _annualRate) external; /* onlyMigrationOwner */
/// Returns the annual withdraw rate of the pool
/// @return annualRate is the maximum annual rate that can be withdrawn
function getMaxAnnualRate() external view returns (uint256);
/// Resets the outstanding tokens to new start time
/// @dev governance function called only by the migration owner
/// @dev the next duration will be calculated starting from the given time
/// @param startTime is the time to set as the last withdrawal time
function resetOutstandingTokens(uint256 startTime) external; /* onlyMigrationOwner */
/// Emergency withdraw the wallet funds
/// @dev governance function called only by the migration owner
/// @dev used in emergencies, when a migration to a new wallet is needed
/// @param erc20 is the erc20 address of the token to withdraw
function emergencyWithdraw(address erc20) external; /* onlyMigrationOwner */
/// Sets the address of the client that can withdraw funds
/// @dev governance function called only by the functional owner
/// @param _client is the address of the new client
function setClient(address _client) external; /* onlyFunctionalOwner */
}
// File: contracts/spec_interfaces/IStakingRewards.sol
pragma solidity 0.6.12;
/// @title Staking rewards contract interface
interface IStakingRewards {
event DelegatorStakingRewardsAssigned(address indexed delegator, uint256 amount, uint256 totalAwarded, address guardian, uint256 delegatorRewardsPerToken, uint256 delegatorRewardsPerTokenDelta);
event GuardianStakingRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, uint256 delegatorRewardsPerToken, uint256 delegatorRewardsPerTokenDelta, uint256 stakingRewardsPerWeight, uint256 stakingRewardsPerWeightDelta);
event StakingRewardsClaimed(address indexed addr, uint256 claimedDelegatorRewards, uint256 claimedGuardianRewards, uint256 totalClaimedDelegatorRewards, uint256 totalClaimedGuardianRewards);
event StakingRewardsAllocated(uint256 allocatedRewards, uint256 stakingRewardsPerWeight);
event GuardianDelegatorsStakingRewardsPercentMilleUpdated(address indexed guardian, uint256 delegatorsStakingRewardsPercentMille);
/*
* External functions
*/
/// Returns the current reward balance of the given address.
/// @dev calculates the up to date balances (differ from the state)
/// @param addr is the address to query
/// @return delegatorStakingRewardsBalance the rewards awarded to the guardian role
/// @return guardianStakingRewardsBalance the rewards awarded to the guardian role
function getStakingRewardsBalance(address addr) external view returns (uint256 delegatorStakingRewardsBalance, uint256 guardianStakingRewardsBalance);
/// Claims the staking rewards balance of an addr, staking the rewards
/// @dev Claimed rewards are staked in the staking contract using the distributeRewards interface
/// @dev includes the rewards for both the delegator and guardian roles
/// @dev calculates the up to date rewards prior to distribute them to the staking contract
/// @param addr is the address to claim rewards for
function claimStakingRewards(address addr) external;
/// Returns the current global staking rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @return stakingRewardsPerWeight is the potential reward per 1E18 (TOKEN_BASE) committee weight assigned to a guardian was in the committee from day zero
/// @return unclaimedStakingRewards is the of tokens that were assigned to participants and not claimed yet
function getStakingRewardsState() external view returns (
uint96 stakingRewardsPerWeight,
uint96 unclaimedStakingRewards
);
/// Returns the current guardian staking rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @dev notice that the guardian rewards are the rewards for the guardian role as guardian and do not include delegation rewards
/// @dev use getDelegatorStakingRewardsData to get the guardian's rewards as delegator
/// @param guardian is the guardian to query
/// @return balance is the staking rewards balance for the guardian role
/// @return claimed is the staking rewards for the guardian role that were claimed
/// @return delegatorRewardsPerToken is the potential reward per token (1E18 units) assigned to a guardian's delegator that delegated from day zero
/// @return delegatorRewardsPerTokenDelta is the increment in delegatorRewardsPerToken since the last guardian update
/// @return lastStakingRewardsPerWeight is the up to date stakingRewardsPerWeight used for the guardian state calculation
/// @return stakingRewardsPerWeightDelta is the increment in stakingRewardsPerWeight since the last guardian update
function getGuardianStakingRewardsData(address guardian) external view returns (
uint256 balance,
uint256 claimed,
uint256 delegatorRewardsPerToken,
uint256 delegatorRewardsPerTokenDelta,
uint256 lastStakingRewardsPerWeight,
uint256 stakingRewardsPerWeightDelta
);
/// Returns the current delegator staking rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @param delegator is the delegator to query
/// @return balance is the staking rewards balance for the delegator role
/// @return claimed is the staking rewards for the delegator role that were claimed
/// @return guardian is the guardian the delegator delegated to receiving a portion of the guardian staking rewards
/// @return lastDelegatorRewardsPerToken is the up to date delegatorRewardsPerToken used for the delegator state calculation
/// @return delegatorRewardsPerTokenDelta is the increment in delegatorRewardsPerToken since the last delegator update
function getDelegatorStakingRewardsData(address delegator) external view returns (
uint256 balance,
uint256 claimed,
address guardian,
uint256 lastDelegatorRewardsPerToken,
uint256 delegatorRewardsPerTokenDelta
);
/// Returns an estimation for the delegator and guardian staking rewards for a given duration
/// @dev the returned value is an estimation, assuming no change in the PoS state
/// @dev the period calculated for start from the current block time until the current time + duration.
/// @param addr is the address to estimate rewards for
/// @param duration is the duration to calculate for in seconds
/// @return estimatedDelegatorStakingRewards is the estimated reward for the delegator role
/// @return estimatedGuardianStakingRewards is the estimated reward for the guardian role
function estimateFutureRewards(address addr, uint256 duration) external view returns (
uint256 estimatedDelegatorStakingRewards,
uint256 estimatedGuardianStakingRewards
);
/// Sets the guardian's delegators staking reward portion
/// @dev by default uses the defaultDelegatorsStakingRewardsPercentMille
/// @param delegatorRewardsPercentMille is the delegators portion in percent-mille (0 - maxDelegatorsStakingRewardsPercentMille)
function setGuardianDelegatorsStakingRewardsPercentMille(uint32 delegatorRewardsPercentMille) external;
/// Returns a guardian's delegators staking reward portion
/// @dev If not explicitly set, returns the defaultDelegatorsStakingRewardsPercentMille
/// @return delegatorRewardsRatioPercentMille is the delegators portion in percent-mille
function getGuardianDelegatorsStakingRewardsPercentMille(address guardian) external view returns (uint256 delegatorRewardsRatioPercentMille);
/// Returns the amount of ORBS tokens in the staking rewards wallet allocated to staking rewards
/// @dev The staking wallet balance must always larger than the allocated value
/// @return allocated is the amount of tokens allocated in the staking rewards wallet
function getStakingRewardsWalletAllocatedTokens() external view returns (uint256 allocated);
/// Returns the current annual staking reward rate
/// @dev calculated based on the current total committee weight
/// @return annualRate is the current staking reward rate in percent-mille
function getCurrentStakingRewardsRatePercentMille() external view returns (uint256 annualRate);
/// Notifies an expected change in the committee membership of the guardian
/// @dev Called only by: the Committee contract
/// @dev called upon expected change in the committee membership of the guardian
/// @dev triggers update of the global rewards state and the guardian rewards state
/// @dev updates the rewards state based on the committee state prior to the change
/// @param guardian is the guardian who's committee membership is updated
/// @param weight is the weight of the guardian prior to the change
/// @param totalCommitteeWeight is the total committee weight prior to the change
/// @param inCommittee indicates whether the guardian was in the committee prior to the change
/// @param inCommitteeAfter indicates whether the guardian is in the committee after the change
function committeeMembershipWillChange(address guardian, uint256 weight, uint256 totalCommitteeWeight, bool inCommittee, bool inCommitteeAfter) external /* onlyCommitteeContract */;
/// Notifies an expected change in a delegator and his guardian delegation state
/// @dev Called only by: the Delegation contract
/// @dev called upon expected change in a delegator's delegation state
/// @dev triggers update of the global rewards state, the guardian rewards state and the delegator rewards state
/// @dev on delegation change, updates also the new guardian and the delegator's lastDelegatorRewardsPerToken accordingly
/// @param guardian is the delegator's guardian prior to the change
/// @param guardianDelegatedStake is the delegated stake of the delegator's guardian prior to the change
/// @param delegator is the delegator about to change delegation state
/// @param delegatorStake is the stake of the delegator
/// @param nextGuardian is the delegator's guardian after to the change
/// @param nextGuardianDelegatedStake is the delegated stake of the delegator's guardian after to the change
function delegationWillChange(address guardian, uint256 guardianDelegatedStake, address delegator, uint256 delegatorStake, address nextGuardian, uint256 nextGuardianDelegatedStake) external /* onlyDelegationsContract */;
/*
* Governance functions
*/
event AnnualStakingRewardsRateChanged(uint256 annualRateInPercentMille, uint256 annualCap);
event DefaultDelegatorsStakingRewardsChanged(uint32 defaultDelegatorsStakingRewardsPercentMille);
event MaxDelegatorsStakingRewardsChanged(uint32 maxDelegatorsStakingRewardsPercentMille);
event RewardDistributionActivated(uint256 startTime);
event RewardDistributionDeactivated();
event StakingRewardsBalanceMigrated(address indexed addr, uint256 guardianStakingRewards, uint256 delegatorStakingRewards, address toRewardsContract);
event StakingRewardsBalanceMigrationAccepted(address from, address indexed addr, uint256 guardianStakingRewards, uint256 delegatorStakingRewards);
event EmergencyWithdrawal(address addr, address token);
/// Activates staking rewards allocation
/// @dev governance function called only by the initialization admin
/// @dev On migrations, startTime should be set to the previous contract deactivation time
/// @param startTime sets the last assignment time
function activateRewardDistribution(uint startTime) external /* onlyInitializationAdmin */;
/// Deactivates fees and bootstrap allocation
/// @dev governance function called only by the migration manager
/// @dev guardians updates remain active based on the current perMember value
function deactivateRewardDistribution() external /* onlyMigrationManager */;
/// Sets the default delegators staking reward portion
/// @dev governance function called only by the functional manager
/// @param defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille(0 - maxDelegatorsStakingRewardsPercentMille)
function setDefaultDelegatorsStakingRewardsPercentMille(uint32 defaultDelegatorsStakingRewardsPercentMille) external /* onlyFunctionalManager */;
/// Returns the default delegators staking reward portion
/// @return defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille
function getDefaultDelegatorsStakingRewardsPercentMille() external view returns (uint32);
/// Sets the maximum delegators staking reward portion
/// @dev governance function called only by the functional manager
/// @param maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille(0 - 100,000)
function setMaxDelegatorsStakingRewardsPercentMille(uint32 maxDelegatorsStakingRewardsPercentMille) external /* onlyFunctionalManager */;
/// Returns the default delegators staking reward portion
/// @return maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille
function getMaxDelegatorsStakingRewardsPercentMille() external view returns (uint32);
/// Sets the annual rate and cap for the staking reward
/// @dev governance function called only by the functional manager
/// @param annualRateInPercentMille is the annual rate in percent-mille
/// @param annualCap is the annual staking rewards cap
function setAnnualStakingRewardsRate(uint32 annualRateInPercentMille, uint96 annualCap) external /* onlyFunctionalManager */;
/// Returns the annual staking reward rate
/// @return annualStakingRewardsRatePercentMille is the annual rate in percent-mille
function getAnnualStakingRewardsRatePercentMille() external view returns (uint32);
/// Returns the annual staking rewards cap
/// @return annualStakingRewardsCap is the annual rate in percent-mille
function getAnnualStakingRewardsCap() external view returns (uint256);
/// Checks if rewards allocation is active
/// @return rewardAllocationActive is a bool that indicates that rewards allocation is active
function isRewardAllocationActive() external view returns (bool);
/// Returns the contract's settings
/// @return annualStakingRewardsCap is the annual rate in percent-mille
/// @return annualStakingRewardsRatePercentMille is the annual rate in percent-mille
/// @return defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille
/// @return maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille
/// @return rewardAllocationActive is a bool that indicates that rewards allocation is active
function getSettings() external view returns (
uint annualStakingRewardsCap,
uint32 annualStakingRewardsRatePercentMille,
uint32 defaultDelegatorsStakingRewardsPercentMille,
uint32 maxDelegatorsStakingRewardsPercentMille,
bool rewardAllocationActive
);
/// Migrates the staking rewards balance of the given addresses to a new staking rewards contract
/// @dev The new rewards contract is determined according to the contracts registry
/// @dev No impact of the calling contract if the currently configured contract in the registry
/// @dev may be called also while the contract is locked
/// @param addrs is the list of addresses to migrate
function migrateRewardsBalance(address[] calldata addrs) external;
/// Accepts addresses balance migration from a previous rewards contract
/// @dev the function may be called by any caller that approves the amounts provided for transfer
/// @param addrs is the list migrated addresses
/// @param migratedGuardianStakingRewards is the list of received guardian rewards balance for each address
/// @param migratedDelegatorStakingRewards is the list of received delegator rewards balance for each address
/// @param totalAmount is the total amount of staking rewards migrated for all addresses in the list. Must match the sum of migratedGuardianStakingRewards and migratedDelegatorStakingRewards lists.
function acceptRewardsBalanceMigration(address[] calldata addrs, uint256[] calldata migratedGuardianStakingRewards, uint256[] calldata migratedDelegatorStakingRewards, uint256 totalAmount) external;
/// Performs emergency withdrawal of the contract balance
/// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens
/// @dev governance function called only by the migration manager
/// @param erc20 is the ERC20 token to withdraw
function emergencyWithdraw(address erc20) external /* onlyMigrationManager */;
}
// File: contracts/spec_interfaces/IDelegations.sol
pragma solidity 0.6.12;
/// @title Delegations contract interface
interface IDelegations /* is IStakeChangeNotifier */ {
// Delegation state change events
event DelegatedStakeChanged(address indexed addr, uint256 selfDelegatedStake, uint256 delegatedStake, address indexed delegator, uint256 delegatorContributedStake);
// Function calls
event Delegated(address indexed from, address indexed to);
/*
* External functions
*/
/// Delegate your stake
/// @dev updates the election contract on the changes in the delegated stake
/// @dev updates the rewards contract on the upcoming change in the delegator's delegation state
/// @param to is the address to delegate to
function delegate(address to) external /* onlyWhenActive */;
/// Refresh the address stake for delegation power based on the staking contract
/// @dev Disabled stake change update notifications from the staking contract may create mismatches
/// @dev refreshStake re-syncs the stake data with the staking contract
/// @param addr is the address to refresh its stake
function refreshStake(address addr) external /* onlyWhenActive */;
/// Refresh the addresses stake for delegation power based on the staking contract
/// @dev Batched version of refreshStake
/// @dev Disabled stake change update notifications from the staking contract may create mismatches
/// @dev refreshStakeBatch re-syncs the stake data with the staking contract
/// @param addrs is the list of addresses to refresh their stake
function refreshStakeBatch(address[] calldata addrs) external /* onlyWhenActive */;
/// Returns the delegate address of the given address
/// @param addr is the address to query
/// @return delegation is the address the addr delegated to
function getDelegation(address addr) external view returns (address);
/// Returns a delegator info
/// @param addr is the address to query
/// @return delegation is the address the addr delegated to
/// @return delegatorStake is the stake of the delegator as reflected in the delegation contract
function getDelegationInfo(address addr) external view returns (address delegation, uint256 delegatorStake);
/// Returns the delegated stake of an addr
/// @dev an address that is not self delegating has a 0 delegated stake
/// @param addr is the address to query
/// @return delegatedStake is the address delegated stake
function getDelegatedStake(address addr) external view returns (uint256);
/// Returns the total delegated stake
/// @dev delegatedStake - the total stake delegated to an address that is self delegating
/// @dev the delegated stake of a non self-delegated address is 0
/// @return totalDelegatedStake is the total delegatedStake of all the addresses
function getTotalDelegatedStake() external view returns (uint256) ;
/*
* Governance functions
*/
event DelegationsImported(address[] from, address indexed to);
event DelegationInitialized(address indexed from, address indexed to);
/// Imports delegations during initial migration
/// @dev initialization function called only by the initializationManager
/// @dev Does not update the Rewards or Election contracts
/// @dev assumes deactivated Rewards
/// @param from is a list of delegator addresses
/// @param to is the address the delegators delegate to
function importDelegations(address[] calldata from, address to) external /* onlyMigrationManager onlyDuringDelegationImport */;
/// Initializes the delegation of an address during initial migration
/// @dev initialization function called only by the initializationManager
/// @dev behaves identically to a delegate transaction sent by the delegator
/// @param from is the delegator addresses
/// @param to is the delegator delegates to
function initDelegation(address from, address to) external /* onlyInitializationAdmin */;
}
// File: contracts/IMigratableStakingContract.sol
pragma solidity 0.6.12;
/// @title An interface for staking contracts which support stake migration.
interface IMigratableStakingContract {
/// @dev Returns the address of the underlying staked token.
/// @return IERC20 The address of the token.
function getToken() external view returns (IERC20);
/// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least
/// the required amount using ERC20 approve.
/// @param _stakeOwner address The specified stake owner.
/// @param _amount uint256 The number of tokens to stake.
function acceptMigration(address _stakeOwner, uint256 _amount) external;
event AcceptedMigration(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
}
// File: contracts/IStakingContract.sol
pragma solidity 0.6.12;
/// @title An interface for staking contracts.
interface IStakingContract {
/// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least
/// the required amount using ERC20 approve.
/// @param _amount uint256 The amount of tokens to stake.
function stake(uint256 _amount) external;
/// @dev Unstakes ORBS tokens from msg.sender. If successful, this will start the cooldown period, after which
/// msg.sender would be able to withdraw all of his tokens.
/// @param _amount uint256 The amount of tokens to unstake.
function unstake(uint256 _amount) external;
/// @dev Requests to withdraw all of staked ORBS tokens back to msg.sender. Stake owners can withdraw their ORBS
/// tokens only after previously unstaking them and after the cooldown period has passed (unless the contract was
/// requested to release all stakes).
function withdraw() external;
/// @dev Restakes unstaked ORBS tokens (in or after cooldown) for msg.sender.
function restake() external;
/// @dev Distributes staking rewards to a list of addresses by directly adding rewards to their stakes. This method
/// assumes that the user has already approved at least the required amount using ERC20 approve. Since this is a
/// convenience method, we aren't concerned about reaching block gas limit by using large lists. We assume that
/// callers will be able to properly batch/paginate their requests.
/// @param _totalAmount uint256 The total amount of rewards to distribute.
/// @param _stakeOwners address[] The addresses of the stake owners.
/// @param _amounts uint256[] The amounts of the rewards.
function distributeRewards(uint256 _totalAmount, address[] calldata _stakeOwners, uint256[] calldata _amounts) external;
/// @dev Returns the stake of the specified stake owner (excluding unstaked tokens).
/// @param _stakeOwner address The address to check.
/// @return uint256 The total stake.
function getStakeBalanceOf(address _stakeOwner) external view returns (uint256);
/// @dev Returns the total amount staked tokens (excluding unstaked tokens).
/// @return uint256 The total staked tokens of all stake owners.
function getTotalStakedTokens() external view returns (uint256);
/// @dev Returns the time that the cooldown period ends (or ended) and the amount of tokens to be released.
/// @param _stakeOwner address The address to check.
/// @return cooldownAmount uint256 The total tokens in cooldown.
/// @return cooldownEndTime uint256 The time when the cooldown period ends (in seconds).
function getUnstakeStatus(address _stakeOwner) external view returns (uint256 cooldownAmount,
uint256 cooldownEndTime);
/// @dev Migrates the stake of msg.sender from this staking contract to a new approved staking contract.
/// @param _newStakingContract IMigratableStakingContract The new staking contract which supports stake migration.
/// @param _amount uint256 The amount of tokens to migrate.
function migrateStakedTokens(IMigratableStakingContract _newStakingContract, uint256 _amount) external;
event Staked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
event Unstaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
event Withdrew(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
event Restaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
event MigratedStake(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
}
// File: contracts/spec_interfaces/IManagedContract.sol
pragma solidity 0.6.12;
/// @title managed contract interface, used by the contracts registry to notify the contract on updates
interface IManagedContract /* is ILockable, IContractRegistryAccessor, Initializable */ {
/// Refreshes the address of the other contracts the contract interacts with
/// @dev called by the registry contract upon an update of a contract in the registry
function refreshContracts() external;
}
// File: contracts/spec_interfaces/IContractRegistry.sol
pragma solidity 0.6.12;
/// @title Contract registry contract interface
/// @dev The contract registry holds Orbs PoS contracts and managers lists
/// @dev The contract registry updates the managed contracts on changes in the contract list
/// @dev Governance functions restricted to managers access the registry to retrieve the manager address
/// @dev The contract registry represents the source of truth for Orbs Ethereum contracts
/// @dev By tracking the registry events or query before interaction, one can access the up to date contracts
interface IContractRegistry {
event ContractAddressUpdated(string contractName, address addr, bool managedContract);
event ManagerChanged(string role, address newManager);
event ContractRegistryUpdated(address newContractRegistry);
/*
* External functions
*/
/// Updates the contracts address and emits a corresponding event
/// @dev governance function called only by the migrationManager or registryAdmin
/// @param contractName is the contract name, used to identify it
/// @param addr is the contract updated address
/// @param managedContract indicates whether the contract is managed by the registry and notified on changes
function setContract(string calldata contractName, address addr, bool managedContract) external /* onlyAdminOrMigrationManager */;
/// Returns the current address of the given contracts
/// @param contractName is the contract name, used to identify it
/// @return addr is the contract updated address
function getContract(string calldata contractName) external view returns (address);
/// Returns the list of contract addresses managed by the registry
/// @dev Managed contracts are updated on changes in the registry contracts addresses
/// @return addrs is the list of managed contracts
function getManagedContracts() external view returns (address[] memory);
/// Locks all the managed contracts
/// @dev governance function called only by the migrationManager or registryAdmin
/// @dev When set all onlyWhenActive functions will revert
function lockContracts() external /* onlyAdminOrMigrationManager */;
/// Unlocks all the managed contracts
/// @dev governance function called only by the migrationManager or registryAdmin
function unlockContracts() external /* onlyAdminOrMigrationManager */;
/// Updates a manager address and emits a corresponding event
/// @dev governance function called only by the registryAdmin
/// @dev the managers list is a flexible list of role to the manager's address
/// @param role is the managers' role name, for example "functionalManager"
/// @param manager is the manager updated address
function setManager(string calldata role, address manager) external /* onlyAdmin */;
/// Returns the current address of the given manager
/// @param role is the manager name, used to identify it
/// @return addr is the manager updated address
function getManager(string calldata role) external view returns (address);
/// Sets a new contract registry to migrate to
/// @dev governance function called only by the registryAdmin
/// @dev updates the registry address record in all the managed contracts
/// @dev by tracking the emitted ContractRegistryUpdated, tools can track the up to date contracts
/// @param newRegistry is the new registry contract
function setNewContractRegistry(IContractRegistry newRegistry) external /* onlyAdmin */;
/// Returns the previous contract registry address
/// @dev used when the setting the contract as a new registry to assure a valid registry
/// @return previousContractRegistry is the previous contract registry
function getPreviousContractRegistry() external view returns (address);
}
// File: contracts/spec_interfaces/IContractRegistryAccessor.sol
pragma solidity 0.6.12;
interface IContractRegistryAccessor {
/// Sets the contract registry address
/// @dev governance function called only by an admin
/// @param newRegistry is the new registry contract
function setContractRegistry(IContractRegistry newRegistry) external /* onlyAdmin */;
/// Returns the contract registry address
/// @return contractRegistry is the contract registry address
function getContractRegistry() external view returns (IContractRegistry contractRegistry);
function setRegistryAdmin(address _registryAdmin) external /* onlyInitializationAdmin */;
}
// 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: contracts/WithClaimableRegistryManagement.sol
pragma solidity 0.6.12;
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract WithClaimableRegistryManagement is Context {
address private _registryAdmin;
address private _pendingRegistryAdmin;
event RegistryManagementTransferred(address indexed previousRegistryAdmin, address indexed newRegistryAdmin);
/**
* @dev Initializes the contract setting the deployer as the initial registryRegistryAdmin.
*/
constructor () internal {
address msgSender = _msgSender();
_registryAdmin = msgSender;
emit RegistryManagementTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current registryAdmin.
*/
function registryAdmin() public view returns (address) {
return _registryAdmin;
}
/**
* @dev Throws if called by any account other than the registryAdmin.
*/
modifier onlyRegistryAdmin() {
require(isRegistryAdmin(), "WithClaimableRegistryManagement: caller is not the registryAdmin");
_;
}
/**
* @dev Returns true if the caller is the current registryAdmin.
*/
function isRegistryAdmin() public view returns (bool) {
return _msgSender() == _registryAdmin;
}
/**
* @dev Leaves the contract without registryAdmin. It will not be possible to call
* `onlyManager` functions anymore. Can only be called by the current registryAdmin.
*
* NOTE: Renouncing registryManagement will leave the contract without an registryAdmin,
* thereby removing any functionality that is only available to the registryAdmin.
*/
function renounceRegistryManagement() public onlyRegistryAdmin {
emit RegistryManagementTransferred(_registryAdmin, address(0));
_registryAdmin = address(0);
}
/**
* @dev Transfers registryManagement of the contract to a new account (`newManager`).
*/
function _transferRegistryManagement(address newRegistryAdmin) internal {
require(newRegistryAdmin != address(0), "RegistryAdmin: new registryAdmin is the zero address");
emit RegistryManagementTransferred(_registryAdmin, newRegistryAdmin);
_registryAdmin = newRegistryAdmin;
}
/**
* @dev Modifier throws if called by any account other than the pendingManager.
*/
modifier onlyPendingRegistryAdmin() {
require(msg.sender == _pendingRegistryAdmin, "Caller is not the pending registryAdmin");
_;
}
/**
* @dev Allows the current registryAdmin to set the pendingManager address.
* @param newRegistryAdmin The address to transfer registryManagement to.
*/
function transferRegistryManagement(address newRegistryAdmin) public onlyRegistryAdmin {
_pendingRegistryAdmin = newRegistryAdmin;
}
/**
* @dev Allows the _pendingRegistryAdmin address to finalize the transfer.
*/
function claimRegistryManagement() external onlyPendingRegistryAdmin {
_transferRegistryManagement(_pendingRegistryAdmin);
_pendingRegistryAdmin = address(0);
}
/**
* @dev Returns the current pendingRegistryAdmin
*/
function pendingRegistryAdmin() public view returns (address) {
return _pendingRegistryAdmin;
}
}
// File: contracts/Initializable.sol
pragma solidity 0.6.12;
contract Initializable {
address private _initializationAdmin;
event InitializationComplete();
/// Constructor
/// Sets the initializationAdmin to the contract deployer
/// The initialization admin may call any manager only function until initializationComplete
constructor() public{
_initializationAdmin = msg.sender;
}
modifier onlyInitializationAdmin() {
require(msg.sender == initializationAdmin(), "sender is not the initialization admin");
_;
}
/*
* External functions
*/
/// Returns the initializationAdmin address
function initializationAdmin() public view returns (address) {
return _initializationAdmin;
}
/// Finalizes the initialization and revokes the initializationAdmin role
function initializationComplete() external onlyInitializationAdmin {
_initializationAdmin = address(0);
emit InitializationComplete();
}
/// Checks if the initialization was completed
function isInitializationComplete() public view returns (bool) {
return _initializationAdmin == address(0);
}
}
// File: contracts/ContractRegistryAccessor.sol
pragma solidity 0.6.12;
contract ContractRegistryAccessor is IContractRegistryAccessor, WithClaimableRegistryManagement, Initializable {
IContractRegistry private contractRegistry;
/// Constructor
/// @param _contractRegistry is the contract registry address
/// @param _registryAdmin is the registry admin address
constructor(IContractRegistry _contractRegistry, address _registryAdmin) public {
require(address(_contractRegistry) != address(0), "_contractRegistry cannot be 0");
setContractRegistry(_contractRegistry);
_transferRegistryManagement(_registryAdmin);
}
modifier onlyAdmin {
require(isAdmin(), "sender is not an admin (registryManger or initializationAdmin)");
_;
}
modifier onlyMigrationManager {
require(isMigrationManager(), "sender is not the migration manager");
_;
}
modifier onlyFunctionalManager {
require(isFunctionalManager(), "sender is not the functional manager");
_;
}
/// Checks whether the caller is Admin: either the contract registry, the registry admin, or the initialization admin
function isAdmin() internal view returns (bool) {
return msg.sender == address(contractRegistry) || msg.sender == registryAdmin() || msg.sender == initializationAdmin();
}
/// Checks whether the caller is a specific manager role or and Admin
/// @dev queries the registry contract for the up to date manager assignment
function isManager(string memory role) internal view returns (bool) {
IContractRegistry _contractRegistry = contractRegistry;
return isAdmin() || _contractRegistry != IContractRegistry(0) && contractRegistry.getManager(role) == msg.sender;
}
/// Checks whether the caller is the migration manager
function isMigrationManager() internal view returns (bool) {
return isManager('migrationManager');
}
/// Checks whether the caller is the functional manager
function isFunctionalManager() internal view returns (bool) {
return isManager('functionalManager');
}
/*
* Contract getters, return the address of a contract by calling the contract registry
*/
function getProtocolContract() internal view returns (address) {
return contractRegistry.getContract("protocol");
}
function getStakingRewardsContract() internal view returns (address) {
return contractRegistry.getContract("stakingRewards");
}
function getFeesAndBootstrapRewardsContract() internal view returns (address) {
return contractRegistry.getContract("feesAndBootstrapRewards");
}
function getCommitteeContract() internal view returns (address) {
return contractRegistry.getContract("committee");
}
function getElectionsContract() internal view returns (address) {
return contractRegistry.getContract("elections");
}
function getDelegationsContract() internal view returns (address) {
return contractRegistry.getContract("delegations");
}
function getGuardiansRegistrationContract() internal view returns (address) {
return contractRegistry.getContract("guardiansRegistration");
}
function getCertificationContract() internal view returns (address) {
return contractRegistry.getContract("certification");
}
function getStakingContract() internal view returns (address) {
return contractRegistry.getContract("staking");
}
function getSubscriptionsContract() internal view returns (address) {
return contractRegistry.getContract("subscriptions");
}
function getStakingRewardsWallet() internal view returns (address) {
return contractRegistry.getContract("stakingRewardsWallet");
}
function getBootstrapRewardsWallet() internal view returns (address) {
return contractRegistry.getContract("bootstrapRewardsWallet");
}
function getGeneralFeesWallet() internal view returns (address) {
return contractRegistry.getContract("generalFeesWallet");
}
function getCertifiedFeesWallet() internal view returns (address) {
return contractRegistry.getContract("certifiedFeesWallet");
}
function getStakingContractHandler() internal view returns (address) {
return contractRegistry.getContract("stakingContractHandler");
}
/*
* Governance functions
*/
event ContractRegistryAddressUpdated(address addr);
/// Sets the contract registry address
/// @dev governance function called only by an admin
/// @param newContractRegistry is the new registry contract
function setContractRegistry(IContractRegistry newContractRegistry) public override onlyAdmin {
require(newContractRegistry.getPreviousContractRegistry() == address(contractRegistry), "new contract registry must provide the previous contract registry");
contractRegistry = newContractRegistry;
emit ContractRegistryAddressUpdated(address(newContractRegistry));
}
/// Returns the contract registry that the contract is set to use
/// @return contractRegistry is the registry contract address
function getContractRegistry() public override view returns (IContractRegistry) {
return contractRegistry;
}
function setRegistryAdmin(address _registryAdmin) external override onlyInitializationAdmin {
_transferRegistryManagement(_registryAdmin);
}
}
// File: contracts/spec_interfaces/ILockable.sol
pragma solidity 0.6.12;
/// @title lockable contract interface, allows to lock a contract
interface ILockable {
event Locked();
event Unlocked();
/// Locks the contract to external non-governance function calls
/// @dev governance function called only by the migration manager or an admin
/// @dev typically called by the registry contract upon locking all managed contracts
/// @dev getters and migration functions remain active also for locked contracts
/// @dev checked by the onlyWhenActive modifier
function lock() external /* onlyMigrationManager */;
/// Unlocks the contract
/// @dev governance function called only by the migration manager or an admin
/// @dev typically called by the registry contract upon unlocking all managed contracts
function unlock() external /* onlyMigrationManager */;
/// Returns the contract locking status
/// @return isLocked is a bool indicating the contract is locked
function isLocked() view external returns (bool);
}
// File: contracts/Lockable.sol
pragma solidity 0.6.12;
/// @title lockable contract
contract Lockable is ILockable, ContractRegistryAccessor {
bool public locked;
/// Constructor
/// @param _contractRegistry is the contract registry address
/// @param _registryAdmin is the registry admin address
constructor(IContractRegistry _contractRegistry, address _registryAdmin) ContractRegistryAccessor(_contractRegistry, _registryAdmin) public {}
/// Locks the contract to external non-governance function calls
/// @dev governance function called only by the migration manager or an admin
/// @dev typically called by the registry contract upon locking all managed contracts
/// @dev getters and migration functions remain active also for locked contracts
/// @dev checked by the onlyWhenActive modifier
function lock() external override onlyMigrationManager {
locked = true;
emit Locked();
}
/// Unlocks the contract
/// @dev governance function called only by the migration manager or an admin
/// @dev typically called by the registry contract upon unlocking all managed contracts
function unlock() external override onlyMigrationManager {
locked = false;
emit Unlocked();
}
/// Returns the contract locking status
/// @return isLocked is a bool indicating the contract is locked
function isLocked() external override view returns (bool) {
return locked;
}
modifier onlyWhenActive() {
require(!locked, "contract is locked for this operation");
_;
}
}
// File: contracts/ManagedContract.sol
pragma solidity 0.6.12;
/// @title managed contract
contract ManagedContract is IManagedContract, Lockable {
/// @param _contractRegistry is the contract registry address
/// @param _registryAdmin is the registry admin address
constructor(IContractRegistry _contractRegistry, address _registryAdmin) Lockable(_contractRegistry, _registryAdmin) public {}
/// Refreshes the address of the other contracts the contract interacts with
/// @dev called by the registry contract upon an update of a contract in the registry
function refreshContracts() virtual override external {}
}
// File: contracts/StakingRewards.sol
pragma solidity 0.6.12;
contract StakingRewards is IStakingRewards, ManagedContract {
using SafeMath for uint256;
using SafeMath96 for uint96;
uint256 constant PERCENT_MILLIE_BASE = 100000;
uint256 constant TOKEN_BASE = 1e18;
struct Settings {
uint96 annualCap;
uint32 annualRateInPercentMille;
uint32 defaultDelegatorsStakingRewardsPercentMille;
uint32 maxDelegatorsStakingRewardsPercentMille;
bool rewardAllocationActive;
}
Settings settings;
IERC20 public token;
struct StakingRewardsState {
uint96 stakingRewardsPerWeight;
uint96 unclaimedStakingRewards;
uint32 lastAssigned;
}
StakingRewardsState public stakingRewardsState;
uint256 public stakingRewardsContractBalance;
struct GuardianStakingRewards {
uint96 delegatorRewardsPerToken;
uint96 lastStakingRewardsPerWeight;
uint96 balance;
uint96 claimed;
}
mapping(address => GuardianStakingRewards) public guardiansStakingRewards;
struct GuardianRewardSettings {
uint32 delegatorsStakingRewardsPercentMille;
bool overrideDefault;
}
mapping(address => GuardianRewardSettings) public guardiansRewardSettings;
struct DelegatorStakingRewards {
uint96 balance;
uint96 lastDelegatorRewardsPerToken;
uint96 claimed;
}
mapping(address => DelegatorStakingRewards) public delegatorsStakingRewards;
/// Constructor
/// @dev the constructor does not migrate reward balances from the previous rewards contract
/// @param _contractRegistry is the contract registry address
/// @param _registryAdmin is the registry admin address
/// @param _token is the token used for staking rewards
/// @param annualRateInPercentMille is the annual rate in percent-mille
/// @param annualCap is the annual staking rewards cap
/// @param defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille(0 - maxDelegatorsStakingRewardsPercentMille)
/// @param maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille(0 - 100,000)
/// @param previousRewardsContract is the previous rewards contract address used for migration of guardians settings. address(0) indicates no guardian settings to migrate
/// @param guardiansToMigrate is a list of guardian addresses to migrate their rewards settings
constructor(
IContractRegistry _contractRegistry,
address _registryAdmin,
IERC20 _token,
uint32 annualRateInPercentMille,
uint96 annualCap,
uint32 defaultDelegatorsStakingRewardsPercentMille,
uint32 maxDelegatorsStakingRewardsPercentMille,
IStakingRewards previousRewardsContract,
address[] memory guardiansToMigrate
) ManagedContract(_contractRegistry, _registryAdmin) public {
require(address(_token) != address(0), "token must not be 0");
_setAnnualStakingRewardsRate(annualRateInPercentMille, annualCap);
setMaxDelegatorsStakingRewardsPercentMille(maxDelegatorsStakingRewardsPercentMille);
setDefaultDelegatorsStakingRewardsPercentMille(defaultDelegatorsStakingRewardsPercentMille);
token = _token;
if (address(previousRewardsContract) != address(0)) {
migrateGuardiansSettings(previousRewardsContract, guardiansToMigrate);
}
}
modifier onlyCommitteeContract() {
require(msg.sender == address(committeeContract), "caller is not the elections contract");
_;
}
modifier onlyDelegationsContract() {
require(msg.sender == address(delegationsContract), "caller is not the delegations contract");
_;
}
/*
* External functions
*/
/// Returns the current reward balance of the given address.
/// @dev calculates the up to date balances (differ from the state)
/// @param addr is the address to query
/// @return delegatorStakingRewardsBalance the rewards awarded to the guardian role
/// @return guardianStakingRewardsBalance the rewards awarded to the guardian role
function getStakingRewardsBalance(address addr) external override view returns (uint256 delegatorStakingRewardsBalance, uint256 guardianStakingRewardsBalance) {
(DelegatorStakingRewards memory delegatorStakingRewards,,) = getDelegatorStakingRewards(addr, block.timestamp);
(GuardianStakingRewards memory guardianStakingRewards,,) = getGuardianStakingRewards(addr, block.timestamp);
return (delegatorStakingRewards.balance, guardianStakingRewards.balance);
}
/// Claims the staking rewards balance of an addr, staking the rewards
/// @dev Claimed rewards are staked in the staking contract using the distributeRewards interface
/// @dev includes the rewards for both the delegator and guardian roles
/// @dev calculates the up to date rewards prior to distribute them to the staking contract
/// @param addr is the address to claim rewards for
function claimStakingRewards(address addr) external override onlyWhenActive {
(uint256 guardianRewards, uint256 delegatorRewards) = claimStakingRewardsLocally(addr);
uint256 total = delegatorRewards.add(guardianRewards);
if (total == 0) {
return;
}
uint96 claimedGuardianRewards = guardiansStakingRewards[addr].claimed.add(guardianRewards);
guardiansStakingRewards[addr].claimed = claimedGuardianRewards;
uint96 claimedDelegatorRewards = delegatorsStakingRewards[addr].claimed.add(delegatorRewards);
delegatorsStakingRewards[addr].claimed = claimedDelegatorRewards;
require(token.approve(address(stakingContract), total), "claimStakingRewards: approve failed");
address[] memory addrs = new address[](1);
addrs[0] = addr;
uint256[] memory amounts = new uint256[](1);
amounts[0] = total;
stakingContract.distributeRewards(total, addrs, amounts);
emit StakingRewardsClaimed(addr, delegatorRewards, guardianRewards, claimedDelegatorRewards, claimedGuardianRewards);
}
/// Returns the current global staking rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @return stakingRewardsPerWeight is the potential reward per 1E18 (TOKEN_BASE) committee weight assigned to a guardian was in the committee from day zero
/// @return unclaimedStakingRewards is the of tokens that were assigned to participants and not claimed yet
function getStakingRewardsState() public override view returns (
uint96 stakingRewardsPerWeight,
uint96 unclaimedStakingRewards
) {
(, , uint totalCommitteeWeight) = committeeContract.getCommitteeStats();
(StakingRewardsState memory _stakingRewardsState,) = _getStakingRewardsState(totalCommitteeWeight, block.timestamp, settings);
stakingRewardsPerWeight = _stakingRewardsState.stakingRewardsPerWeight;
unclaimedStakingRewards = _stakingRewardsState.unclaimedStakingRewards;
}
/// Returns the current guardian staking rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @dev notice that the guardian rewards are the rewards for the guardian role as guardian and do not include delegation rewards
/// @dev use getDelegatorStakingRewardsData to get the guardian's rewards as delegator
/// @param guardian is the guardian to query
/// @return balance is the staking rewards balance for the guardian role
/// @return claimed is the staking rewards for the guardian role that were claimed
/// @return delegatorRewardsPerToken is the potential reward per token (1E18 units) assigned to a guardian's delegator that delegated from day zero
/// @return delegatorRewardsPerTokenDelta is the increment in delegatorRewardsPerToken since the last guardian update
/// @return lastStakingRewardsPerWeight is the up to date stakingRewardsPerWeight used for the guardian state calculation
/// @return stakingRewardsPerWeightDelta is the increment in stakingRewardsPerWeight since the last guardian update
function getGuardianStakingRewardsData(address guardian) external override view returns (
uint256 balance,
uint256 claimed,
uint256 delegatorRewardsPerToken,
uint256 delegatorRewardsPerTokenDelta,
uint256 lastStakingRewardsPerWeight,
uint256 stakingRewardsPerWeightDelta
) {
(GuardianStakingRewards memory rewards, uint256 _stakingRewardsPerWeightDelta, uint256 _delegatorRewardsPerTokenDelta) = getGuardianStakingRewards(guardian, block.timestamp);
return (rewards.balance, rewards.claimed, rewards.delegatorRewardsPerToken, _delegatorRewardsPerTokenDelta, rewards.lastStakingRewardsPerWeight, _stakingRewardsPerWeightDelta);
}
/// Returns the current delegator staking rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @param delegator is the delegator to query
/// @return balance is the staking rewards balance for the delegator role
/// @return claimed is the staking rewards for the delegator role that were claimed
/// @return guardian is the guardian the delegator delegated to receiving a portion of the guardian staking rewards
/// @return lastDelegatorRewardsPerToken is the up to date delegatorRewardsPerToken used for the delegator state calculation
/// @return delegatorRewardsPerTokenDelta is the increment in delegatorRewardsPerToken since the last delegator update
function getDelegatorStakingRewardsData(address delegator) external override view returns (
uint256 balance,
uint256 claimed,
address guardian,
uint256 lastDelegatorRewardsPerToken,
uint256 delegatorRewardsPerTokenDelta
) {
(DelegatorStakingRewards memory rewards, address _guardian, uint256 _delegatorRewardsPerTokenDelta) = getDelegatorStakingRewards(delegator, block.timestamp);
return (rewards.balance, rewards.claimed, _guardian, rewards.lastDelegatorRewardsPerToken, _delegatorRewardsPerTokenDelta);
}
/// Returns an estimation for the delegator and guardian staking rewards for a given duration
/// @dev the returned value is an estimation, assuming no change in the PoS state
/// @dev the period calculated for start from the current block time until the current time + duration.
/// @param addr is the address to estimate rewards for
/// @param duration is the duration to calculate for in seconds
/// @return estimatedDelegatorStakingRewards is the estimated reward for the delegator role
/// @return estimatedGuardianStakingRewards is the estimated reward for the guardian role
function estimateFutureRewards(address addr, uint256 duration) external override view returns (uint256 estimatedDelegatorStakingRewards, uint256 estimatedGuardianStakingRewards) {
(GuardianStakingRewards memory guardianRewardsNow,,) = getGuardianStakingRewards(addr, block.timestamp);
(DelegatorStakingRewards memory delegatorRewardsNow,,) = getDelegatorStakingRewards(addr, block.timestamp);
(GuardianStakingRewards memory guardianRewardsFuture,,) = getGuardianStakingRewards(addr, block.timestamp.add(duration));
(DelegatorStakingRewards memory delegatorRewardsFuture,,) = getDelegatorStakingRewards(addr, block.timestamp.add(duration));
estimatedDelegatorStakingRewards = delegatorRewardsFuture.balance.sub(delegatorRewardsNow.balance);
estimatedGuardianStakingRewards = guardianRewardsFuture.balance.sub(guardianRewardsNow.balance);
}
/// Sets the guardian's delegators staking reward portion
/// @dev by default uses the defaultDelegatorsStakingRewardsPercentMille
/// @param delegatorRewardsPercentMille is the delegators portion in percent-mille (0 - maxDelegatorsStakingRewardsPercentMille)
function setGuardianDelegatorsStakingRewardsPercentMille(uint32 delegatorRewardsPercentMille) external override onlyWhenActive {
require(delegatorRewardsPercentMille <= PERCENT_MILLIE_BASE, "delegatorRewardsPercentMille must be 100000 at most");
require(delegatorRewardsPercentMille <= settings.maxDelegatorsStakingRewardsPercentMille, "delegatorRewardsPercentMille must not be larger than maxDelegatorsStakingRewardsPercentMille");
updateDelegatorStakingRewards(msg.sender);
_setGuardianDelegatorsStakingRewardsPercentMille(msg.sender, delegatorRewardsPercentMille);
}
/// Returns a guardian's delegators staking reward portion
/// @dev If not explicitly set, returns the defaultDelegatorsStakingRewardsPercentMille
/// @return delegatorRewardsRatioPercentMille is the delegators portion in percent-mille
function getGuardianDelegatorsStakingRewardsPercentMille(address guardian) external override view returns (uint256 delegatorRewardsRatioPercentMille) {
return _getGuardianDelegatorsStakingRewardsPercentMille(guardian, settings);
}
/// Returns the amount of ORBS tokens in the staking rewards wallet allocated to staking rewards
/// @dev The staking wallet balance must always larger than the allocated value
/// @return allocated is the amount of tokens allocated in the staking rewards wallet
function getStakingRewardsWalletAllocatedTokens() external override view returns (uint256 allocated) {
(, uint96 unclaimedStakingRewards) = getStakingRewardsState();
return uint256(unclaimedStakingRewards).sub(stakingRewardsContractBalance);
}
/// Returns the current annual staking reward rate
/// @dev calculated based on the current total committee weight
/// @return annualRate is the current staking reward rate in percent-mille
function getCurrentStakingRewardsRatePercentMille() external override view returns (uint256 annualRate) {
(, , uint totalCommitteeWeight) = committeeContract.getCommitteeStats();
annualRate = _getAnnualRewardPerWeight(totalCommitteeWeight, settings).mul(PERCENT_MILLIE_BASE).div(TOKEN_BASE);
}
/// Notifies an expected change in the committee membership of the guardian
/// @dev Called only by: the Committee contract
/// @dev called upon expected change in the committee membership of the guardian
/// @dev triggers update of the global rewards state and the guardian rewards state
/// @dev updates the rewards state based on the committee state prior to the change
/// @param guardian is the guardian who's committee membership is updated
/// @param weight is the weight of the guardian prior to the change
/// @param totalCommitteeWeight is the total committee weight prior to the change
/// @param inCommittee indicates whether the guardian was in the committee prior to the change
/// @param inCommitteeAfter indicates whether the guardian is in the committee after the change
function committeeMembershipWillChange(address guardian, uint256 weight, uint256 totalCommitteeWeight, bool inCommittee, bool inCommitteeAfter) external override onlyWhenActive onlyCommitteeContract {
uint256 delegatedStake = delegationsContract.getDelegatedStake(guardian);
Settings memory _settings = settings;
StakingRewardsState memory _stakingRewardsState = _updateStakingRewardsState(totalCommitteeWeight, _settings);
_updateGuardianStakingRewards(guardian, inCommittee, inCommitteeAfter, weight, delegatedStake, _stakingRewardsState, _settings);
}
/// Notifies an expected change in a delegator and his guardian delegation state
/// @dev Called only by: the Delegation contract
/// @dev called upon expected change in a delegator's delegation state
/// @dev triggers update of the global rewards state, the guardian rewards state and the delegator rewards state
/// @dev on delegation change, updates also the new guardian and the delegator's lastDelegatorRewardsPerToken accordingly
/// @param guardian is the delegator's guardian prior to the change
/// @param guardianDelegatedStake is the delegated stake of the delegator's guardian prior to the change
/// @param delegator is the delegator about to change delegation state
/// @param delegatorStake is the stake of the delegator
/// @param nextGuardian is the delegator's guardian after to the change
/// @param nextGuardianDelegatedStake is the delegated stake of the delegator's guardian after to the change
function delegationWillChange(address guardian, uint256 guardianDelegatedStake, address delegator, uint256 delegatorStake, address nextGuardian, uint256 nextGuardianDelegatedStake) external override onlyWhenActive onlyDelegationsContract {
Settings memory _settings = settings;
(bool inCommittee, uint256 weight, , uint256 totalCommitteeWeight) = committeeContract.getMemberInfo(guardian);
StakingRewardsState memory _stakingRewardsState = _updateStakingRewardsState(totalCommitteeWeight, _settings);
GuardianStakingRewards memory guardianStakingRewards = _updateGuardianStakingRewards(guardian, inCommittee, inCommittee, weight, guardianDelegatedStake, _stakingRewardsState, _settings);
_updateDelegatorStakingRewards(delegator, delegatorStake, guardian, guardianStakingRewards);
if (nextGuardian != guardian) {
(inCommittee, weight, , totalCommitteeWeight) = committeeContract.getMemberInfo(nextGuardian);
GuardianStakingRewards memory nextGuardianStakingRewards = _updateGuardianStakingRewards(nextGuardian, inCommittee, inCommittee, weight, nextGuardianDelegatedStake, _stakingRewardsState, _settings);
delegatorsStakingRewards[delegator].lastDelegatorRewardsPerToken = nextGuardianStakingRewards.delegatorRewardsPerToken;
}
}
/*
* Governance functions
*/
/// Activates staking rewards allocation
/// @dev governance function called only by the initialization admin
/// @dev On migrations, startTime should be set to the previous contract deactivation time
/// @param startTime sets the last assignment time
function activateRewardDistribution(uint startTime) external override onlyMigrationManager {
require(!settings.rewardAllocationActive, "reward distribution is already activated");
stakingRewardsState.lastAssigned = uint32(startTime);
settings.rewardAllocationActive = true;
emit RewardDistributionActivated(startTime);
}
/// Deactivates fees and bootstrap allocation
/// @dev governance function called only by the migration manager
/// @dev guardians updates remain active based on the current perMember value
function deactivateRewardDistribution() external override onlyMigrationManager {
require(settings.rewardAllocationActive, "reward distribution is already deactivated");
StakingRewardsState memory _stakingRewardsState = updateStakingRewardsState();
settings.rewardAllocationActive = false;
withdrawRewardsWalletAllocatedTokens(_stakingRewardsState);
emit RewardDistributionDeactivated();
}
/// Sets the default delegators staking reward portion
/// @dev governance function called only by the functional manager
/// @param defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille(0 - maxDelegatorsStakingRewardsPercentMille)
function setDefaultDelegatorsStakingRewardsPercentMille(uint32 defaultDelegatorsStakingRewardsPercentMille) public override onlyFunctionalManager {
require(defaultDelegatorsStakingRewardsPercentMille <= PERCENT_MILLIE_BASE, "defaultDelegatorsStakingRewardsPercentMille must not be larger than 100000");
require(defaultDelegatorsStakingRewardsPercentMille <= settings.maxDelegatorsStakingRewardsPercentMille, "defaultDelegatorsStakingRewardsPercentMille must not be larger than maxDelegatorsStakingRewardsPercentMille");
settings.defaultDelegatorsStakingRewardsPercentMille = defaultDelegatorsStakingRewardsPercentMille;
emit DefaultDelegatorsStakingRewardsChanged(defaultDelegatorsStakingRewardsPercentMille);
}
/// Returns the default delegators staking reward portion
/// @return defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille
function getDefaultDelegatorsStakingRewardsPercentMille() public override view returns (uint32) {
return settings.defaultDelegatorsStakingRewardsPercentMille;
}
/// Sets the maximum delegators staking reward portion
/// @dev governance function called only by the functional manager
/// @param maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille(0 - 100,000)
function setMaxDelegatorsStakingRewardsPercentMille(uint32 maxDelegatorsStakingRewardsPercentMille) public override onlyFunctionalManager {
require(maxDelegatorsStakingRewardsPercentMille <= PERCENT_MILLIE_BASE, "maxDelegatorsStakingRewardsPercentMille must not be larger than 100000");
settings.maxDelegatorsStakingRewardsPercentMille = maxDelegatorsStakingRewardsPercentMille;
emit MaxDelegatorsStakingRewardsChanged(maxDelegatorsStakingRewardsPercentMille);
}
/// Returns the default delegators staking reward portion
/// @return maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille
function getMaxDelegatorsStakingRewardsPercentMille() public override view returns (uint32) {
return settings.maxDelegatorsStakingRewardsPercentMille;
}
/// Sets the annual rate and cap for the staking reward
/// @dev governance function called only by the functional manager
/// @param annualRateInPercentMille is the annual rate in percent-mille
/// @param annualCap is the annual staking rewards cap
function setAnnualStakingRewardsRate(uint32 annualRateInPercentMille, uint96 annualCap) external override onlyFunctionalManager {
updateStakingRewardsState();
return _setAnnualStakingRewardsRate(annualRateInPercentMille, annualCap);
}
/// Returns the annual staking reward rate
/// @return annualStakingRewardsRatePercentMille is the annual rate in percent-mille
function getAnnualStakingRewardsRatePercentMille() external override view returns (uint32) {
return settings.annualRateInPercentMille;
}
/// Returns the annual staking rewards cap
/// @return annualStakingRewardsCap is the annual rate in percent-mille
function getAnnualStakingRewardsCap() external override view returns (uint256) {
return settings.annualCap;
}
/// Checks if rewards allocation is active
/// @return rewardAllocationActive is a bool that indicates that rewards allocation is active
function isRewardAllocationActive() external override view returns (bool) {
return settings.rewardAllocationActive;
}
/// Returns the contract's settings
/// @return annualStakingRewardsCap is the annual rate in percent-mille
/// @return annualStakingRewardsRatePercentMille is the annual rate in percent-mille
/// @return defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille
/// @return maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille
/// @return rewardAllocationActive is a bool that indicates that rewards allocation is active
function getSettings() external override view returns (
uint annualStakingRewardsCap,
uint32 annualStakingRewardsRatePercentMille,
uint32 defaultDelegatorsStakingRewardsPercentMille,
uint32 maxDelegatorsStakingRewardsPercentMille,
bool rewardAllocationActive
) {
Settings memory _settings = settings;
annualStakingRewardsCap = _settings.annualCap;
annualStakingRewardsRatePercentMille = _settings.annualRateInPercentMille;
defaultDelegatorsStakingRewardsPercentMille = _settings.defaultDelegatorsStakingRewardsPercentMille;
maxDelegatorsStakingRewardsPercentMille = _settings.maxDelegatorsStakingRewardsPercentMille;
rewardAllocationActive = _settings.rewardAllocationActive;
}
/// Migrates the staking rewards balance of the given addresses to a new staking rewards contract
/// @dev The new rewards contract is determined according to the contracts registry
/// @dev No impact of the calling contract if the currently configured contract in the registry
/// @dev may be called also while the contract is locked
/// @param addrs is the list of addresses to migrate
function migrateRewardsBalance(address[] calldata addrs) external override {
require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration");
IStakingRewards currentRewardsContract = IStakingRewards(getStakingRewardsContract());
require(address(currentRewardsContract) != address(this), "New rewards contract is not set");
uint256 totalAmount = 0;
uint256[] memory guardianRewards = new uint256[](addrs.length);
uint256[] memory delegatorRewards = new uint256[](addrs.length);
for (uint i = 0; i < addrs.length; i++) {
(guardianRewards[i], delegatorRewards[i]) = claimStakingRewardsLocally(addrs[i]);
totalAmount = totalAmount.add(guardianRewards[i]).add(delegatorRewards[i]);
}
require(token.approve(address(currentRewardsContract), totalAmount), "migrateRewardsBalance: approve failed");
currentRewardsContract.acceptRewardsBalanceMigration(addrs, guardianRewards, delegatorRewards, totalAmount);
for (uint i = 0; i < addrs.length; i++) {
emit StakingRewardsBalanceMigrated(addrs[i], guardianRewards[i], delegatorRewards[i], address(currentRewardsContract));
}
}
/// Accepts addresses balance migration from a previous rewards contract
/// @dev the function may be called by any caller that approves the amounts provided for transfer
/// @param addrs is the list migrated addresses
/// @param migratedGuardianStakingRewards is the list of received guardian rewards balance for each address
/// @param migratedDelegatorStakingRewards is the list of received delegator rewards balance for each address
/// @param totalAmount is the total amount of staking rewards migrated for all addresses in the list. Must match the sum of migratedGuardianStakingRewards and migratedDelegatorStakingRewards lists.
function acceptRewardsBalanceMigration(address[] calldata addrs, uint256[] calldata migratedGuardianStakingRewards, uint256[] calldata migratedDelegatorStakingRewards, uint256 totalAmount) external override {
uint256 _totalAmount = 0;
for (uint i = 0; i < addrs.length; i++) {
_totalAmount = _totalAmount.add(migratedGuardianStakingRewards[i]).add(migratedDelegatorStakingRewards[i]);
}
require(totalAmount == _totalAmount, "totalAmount does not match sum of rewards");
if (totalAmount > 0) {
require(token.transferFrom(msg.sender, address(this), totalAmount), "acceptRewardBalanceMigration: transfer failed");
}
for (uint i = 0; i < addrs.length; i++) {
guardiansStakingRewards[addrs[i]].balance = guardiansStakingRewards[addrs[i]].balance.add(migratedGuardianStakingRewards[i]);
delegatorsStakingRewards[addrs[i]].balance = delegatorsStakingRewards[addrs[i]].balance.add(migratedDelegatorStakingRewards[i]);
emit StakingRewardsBalanceMigrationAccepted(msg.sender, addrs[i], migratedGuardianStakingRewards[i], migratedDelegatorStakingRewards[i]);
}
stakingRewardsContractBalance = stakingRewardsContractBalance.add(totalAmount);
stakingRewardsState.unclaimedStakingRewards = stakingRewardsState.unclaimedStakingRewards.add(totalAmount);
}
/// Performs emergency withdrawal of the contract balance
/// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens
/// @dev governance function called only by the migration manager
/// @param erc20 is the ERC20 token to withdraw
function emergencyWithdraw(address erc20) external override onlyMigrationManager {
IERC20 _token = IERC20(erc20);
emit EmergencyWithdrawal(msg.sender, address(_token));
require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "StakingRewards::emergencyWithdraw - transfer failed");
}
/*
* Private functions
*/
// Global state
/// Returns the annual reward per weight
/// @dev calculates the current annual rewards per weight based on the annual rate and annual cap
function _getAnnualRewardPerWeight(uint256 totalCommitteeWeight, Settings memory _settings) private pure returns (uint256) {
return totalCommitteeWeight == 0 ? 0 : Math.min(uint256(_settings.annualRateInPercentMille).mul(TOKEN_BASE).div(PERCENT_MILLIE_BASE), uint256(_settings.annualCap).mul(TOKEN_BASE).div(totalCommitteeWeight));
}
/// Calculates the added rewards per weight for the given duration based on the committee data
/// @param totalCommitteeWeight is the current committee total weight
/// @param duration is the duration to calculate for in seconds
/// @param _settings is the contract settings
function calcStakingRewardPerWeightDelta(uint256 totalCommitteeWeight, uint duration, Settings memory _settings) private pure returns (uint256 stakingRewardsPerWeightDelta) {
stakingRewardsPerWeightDelta = 0;
if (totalCommitteeWeight > 0) {
uint annualRewardPerWeight = _getAnnualRewardPerWeight(totalCommitteeWeight, _settings);
stakingRewardsPerWeightDelta = annualRewardPerWeight.mul(duration).div(365 days);
}
}
/// Returns the up global staking rewards state for a specific time
/// @dev receives the relevant committee data
/// @dev for future time calculations assumes no change in the committee data
/// @param totalCommitteeWeight is the current committee total weight
/// @param currentTime is the time to calculate the rewards for
/// @param _settings is the contract settings
function _getStakingRewardsState(uint256 totalCommitteeWeight, uint256 currentTime, Settings memory _settings) private view returns (StakingRewardsState memory _stakingRewardsState, uint256 allocatedRewards) {
_stakingRewardsState = stakingRewardsState;
if (_settings.rewardAllocationActive) {
uint delta = calcStakingRewardPerWeightDelta(totalCommitteeWeight, currentTime.sub(stakingRewardsState.lastAssigned), _settings);
_stakingRewardsState.stakingRewardsPerWeight = stakingRewardsState.stakingRewardsPerWeight.add(delta);
_stakingRewardsState.lastAssigned = uint32(currentTime);
allocatedRewards = delta.mul(totalCommitteeWeight).div(TOKEN_BASE);
_stakingRewardsState.unclaimedStakingRewards = _stakingRewardsState.unclaimedStakingRewards.add(allocatedRewards);
}
}
/// Updates the global staking rewards
/// @dev calculated to the latest block, may differ from the state read
/// @dev uses the _getStakingRewardsState function
/// @param totalCommitteeWeight is the current committee total weight
/// @param _settings is the contract settings
/// @return _stakingRewardsState is the updated global staking rewards struct
function _updateStakingRewardsState(uint256 totalCommitteeWeight, Settings memory _settings) private returns (StakingRewardsState memory _stakingRewardsState) {
if (!_settings.rewardAllocationActive) {
return stakingRewardsState;
}
uint allocatedRewards;
(_stakingRewardsState, allocatedRewards) = _getStakingRewardsState(totalCommitteeWeight, block.timestamp, _settings);
stakingRewardsState = _stakingRewardsState;
emit StakingRewardsAllocated(allocatedRewards, _stakingRewardsState.stakingRewardsPerWeight);
}
/// Updates the global staking rewards
/// @dev calculated to the latest block, may differ from the state read
/// @dev queries the committee state from the committee contract
/// @dev uses the _updateStakingRewardsState function
/// @return _stakingRewardsState is the updated global staking rewards struct
function updateStakingRewardsState() private returns (StakingRewardsState memory _stakingRewardsState) {
(, , uint totalCommitteeWeight) = committeeContract.getCommitteeStats();
return _updateStakingRewardsState(totalCommitteeWeight, settings);
}
// Guardian state
/// Returns the current guardian staking rewards state
/// @dev receives the relevant committee and guardian data along with the global updated global state
/// @dev calculated to the latest block, may differ from the state read
/// @param guardian is the guardian to query
/// @param inCommittee indicates whether the guardian is currently in the committee
/// @param inCommitteeAfter indicates whether after a potential change the guardian is in the committee
/// @param guardianWeight is the guardian committee weight
/// @param guardianDelegatedStake is the guardian delegated stake
/// @param _stakingRewardsState is the updated global staking rewards state
/// @param _settings is the contract settings
/// @return guardianStakingRewards is the updated guardian staking rewards state
/// @return rewardsAdded is the amount awarded to the guardian since the last update
/// @return stakingRewardsPerWeightDelta is the delta added to the stakingRewardsPerWeight since the last update
/// @return delegatorRewardsPerTokenDelta is the delta added to the guardian's delegatorRewardsPerToken since the last update
function _getGuardianStakingRewards(address guardian, bool inCommittee, bool inCommitteeAfter, uint256 guardianWeight, uint256 guardianDelegatedStake, StakingRewardsState memory _stakingRewardsState, Settings memory _settings) private view returns (GuardianStakingRewards memory guardianStakingRewards, uint256 rewardsAdded, uint256 stakingRewardsPerWeightDelta, uint256 delegatorRewardsPerTokenDelta) {
guardianStakingRewards = guardiansStakingRewards[guardian];
if (inCommittee) {
stakingRewardsPerWeightDelta = uint256(_stakingRewardsState.stakingRewardsPerWeight).sub(guardianStakingRewards.lastStakingRewardsPerWeight);
uint256 totalRewards = stakingRewardsPerWeightDelta.mul(guardianWeight);
uint256 delegatorRewardsRatioPercentMille = _getGuardianDelegatorsStakingRewardsPercentMille(guardian, _settings);
delegatorRewardsPerTokenDelta = guardianDelegatedStake == 0 ? 0 : totalRewards
.div(guardianDelegatedStake)
.mul(delegatorRewardsRatioPercentMille)
.div(PERCENT_MILLIE_BASE);
uint256 guardianCutPercentMille = PERCENT_MILLIE_BASE.sub(delegatorRewardsRatioPercentMille);
rewardsAdded = totalRewards
.mul(guardianCutPercentMille)
.div(PERCENT_MILLIE_BASE)
.div(TOKEN_BASE);
guardianStakingRewards.delegatorRewardsPerToken = guardianStakingRewards.delegatorRewardsPerToken.add(delegatorRewardsPerTokenDelta);
guardianStakingRewards.balance = guardianStakingRewards.balance.add(rewardsAdded);
}
guardianStakingRewards.lastStakingRewardsPerWeight = inCommitteeAfter ? _stakingRewardsState.stakingRewardsPerWeight : 0;
}
/// Returns the guardian staking rewards state for a given time
/// @dev if the time to estimate is in the future, estimates the rewards for the given time
/// @dev for future time estimation assumes no change in the committee and the guardian state
/// @param guardian is the guardian to query
/// @param currentTime is the time to calculate the rewards for
/// @return guardianStakingRewards is the guardian staking rewards state updated to the give time
/// @return stakingRewardsPerWeightDelta is the delta added to the stakingRewardsPerWeight since the last update
/// @return delegatorRewardsPerTokenDelta is the delta added to the guardian's delegatorRewardsPerToken since the last update
function getGuardianStakingRewards(address guardian, uint256 currentTime) private view returns (GuardianStakingRewards memory guardianStakingRewards, uint256 stakingRewardsPerWeightDelta, uint256 delegatorRewardsPerTokenDelta) {
Settings memory _settings = settings;
(bool inCommittee, uint256 guardianWeight, ,uint256 totalCommitteeWeight) = committeeContract.getMemberInfo(guardian);
uint256 guardianDelegatedStake = delegationsContract.getDelegatedStake(guardian);
(StakingRewardsState memory _stakingRewardsState,) = _getStakingRewardsState(totalCommitteeWeight, currentTime, _settings);
(guardianStakingRewards,,stakingRewardsPerWeightDelta,delegatorRewardsPerTokenDelta) = _getGuardianStakingRewards(guardian, inCommittee, inCommittee, guardianWeight, guardianDelegatedStake, _stakingRewardsState, _settings);
}
/// Updates a guardian staking rewards state
/// @dev receives the relevant committee and guardian data along with the global updated global state
/// @dev updates the global staking rewards state prior to calculating the guardian's
/// @dev uses _getGuardianStakingRewards
/// @param guardian is the guardian to update
/// @param inCommittee indicates whether the guardian was in the committee prior to the change
/// @param inCommitteeAfter indicates whether the guardian is in the committee after the change
/// @param guardianWeight is the committee weight of the guardian prior to the change
/// @param guardianDelegatedStake is the delegated stake of the guardian prior to the change
/// @param _stakingRewardsState is the updated global staking rewards state
/// @param _settings is the contract settings
/// @return guardianStakingRewards is the updated guardian staking rewards state
function _updateGuardianStakingRewards(address guardian, bool inCommittee, bool inCommitteeAfter, uint256 guardianWeight, uint256 guardianDelegatedStake, StakingRewardsState memory _stakingRewardsState, Settings memory _settings) private returns (GuardianStakingRewards memory guardianStakingRewards) {
uint256 guardianStakingRewardsAdded;
uint256 stakingRewardsPerWeightDelta;
uint256 delegatorRewardsPerTokenDelta;
(guardianStakingRewards, guardianStakingRewardsAdded, stakingRewardsPerWeightDelta, delegatorRewardsPerTokenDelta) = _getGuardianStakingRewards(guardian, inCommittee, inCommitteeAfter, guardianWeight, guardianDelegatedStake, _stakingRewardsState, _settings);
guardiansStakingRewards[guardian] = guardianStakingRewards;
emit GuardianStakingRewardsAssigned(guardian, guardianStakingRewardsAdded, guardianStakingRewards.claimed.add(guardianStakingRewards.balance), guardianStakingRewards.delegatorRewardsPerToken, delegatorRewardsPerTokenDelta, _stakingRewardsState.stakingRewardsPerWeight, stakingRewardsPerWeightDelta);
}
/// Updates a guardian staking rewards state
/// @dev queries the relevant guardian and committee data from the committee contract
/// @dev uses _updateGuardianStakingRewards
/// @param guardian is the guardian to update
/// @param _stakingRewardsState is the updated global staking rewards state
/// @param _settings is the contract settings
/// @return guardianStakingRewards is the updated guardian staking rewards state
function updateGuardianStakingRewards(address guardian, StakingRewardsState memory _stakingRewardsState, Settings memory _settings) private returns (GuardianStakingRewards memory guardianStakingRewards) {
(bool inCommittee, uint256 guardianWeight,,) = committeeContract.getMemberInfo(guardian);
return _updateGuardianStakingRewards(guardian, inCommittee, inCommittee, guardianWeight, delegationsContract.getDelegatedStake(guardian), _stakingRewardsState, _settings);
}
// Delegator state
/// Returns the current delegator staking rewards state
/// @dev receives the relevant delegator data along with the delegator's current guardian updated global state
/// @dev calculated to the latest block, may differ from the state read
/// @param delegator is the delegator to query
/// @param delegatorStake is the stake of the delegator
/// @param guardianStakingRewards is the updated guardian staking rewards state
/// @return delegatorStakingRewards is the updated delegator staking rewards state
/// @return delegatorRewardsAdded is the amount awarded to the delegator since the last update
/// @return delegatorRewardsPerTokenDelta is the delta added to the delegator's delegatorRewardsPerToken since the last update
function _getDelegatorStakingRewards(address delegator, uint256 delegatorStake, GuardianStakingRewards memory guardianStakingRewards) private view returns (DelegatorStakingRewards memory delegatorStakingRewards, uint256 delegatorRewardsAdded, uint256 delegatorRewardsPerTokenDelta) {
delegatorStakingRewards = delegatorsStakingRewards[delegator];
delegatorRewardsPerTokenDelta = uint256(guardianStakingRewards.delegatorRewardsPerToken)
.sub(delegatorStakingRewards.lastDelegatorRewardsPerToken);
delegatorRewardsAdded = delegatorRewardsPerTokenDelta
.mul(delegatorStake)
.div(TOKEN_BASE);
delegatorStakingRewards.balance = delegatorStakingRewards.balance.add(delegatorRewardsAdded);
delegatorStakingRewards.lastDelegatorRewardsPerToken = guardianStakingRewards.delegatorRewardsPerToken;
}
/// Returns the delegator staking rewards state for a given time
/// @dev if the time to estimate is in the future, estimates the rewards for the given time
/// @dev for future time estimation assumes no change in the committee, delegation and the delegator state
/// @param delegator is the delegator to query
/// @param currentTime is the time to calculate the rewards for
/// @return delegatorStakingRewards is the updated delegator staking rewards state
/// @return guardian is the guardian the delegator delegated to
/// @return delegatorStakingRewardsPerTokenDelta is the delta added to the delegator's delegatorRewardsPerToken since the last update
function getDelegatorStakingRewards(address delegator, uint256 currentTime) private view returns (DelegatorStakingRewards memory delegatorStakingRewards, address guardian, uint256 delegatorStakingRewardsPerTokenDelta) {
uint256 delegatorStake;
(guardian, delegatorStake) = delegationsContract.getDelegationInfo(delegator);
(GuardianStakingRewards memory guardianStakingRewards,,) = getGuardianStakingRewards(guardian, currentTime);
(delegatorStakingRewards,,delegatorStakingRewardsPerTokenDelta) = _getDelegatorStakingRewards(delegator, delegatorStake, guardianStakingRewards);
}
/// Updates a delegator staking rewards state
/// @dev receives the relevant delegator data along with the delegator's current guardian updated global state
/// @dev updates the guardian staking rewards state prior to calculating the delegator's
/// @dev uses _getDelegatorStakingRewards
/// @param delegator is the delegator to update
/// @param delegatorStake is the stake of the delegator
/// @param guardianStakingRewards is the updated guardian staking rewards state
function _updateDelegatorStakingRewards(address delegator, uint256 delegatorStake, address guardian, GuardianStakingRewards memory guardianStakingRewards) private {
uint256 delegatorStakingRewardsAdded;
uint256 delegatorRewardsPerTokenDelta;
DelegatorStakingRewards memory delegatorStakingRewards;
(delegatorStakingRewards, delegatorStakingRewardsAdded, delegatorRewardsPerTokenDelta) = _getDelegatorStakingRewards(delegator, delegatorStake, guardianStakingRewards);
delegatorsStakingRewards[delegator] = delegatorStakingRewards;
emit DelegatorStakingRewardsAssigned(delegator, delegatorStakingRewardsAdded, delegatorStakingRewards.claimed.add(delegatorStakingRewards.balance), guardian, guardianStakingRewards.delegatorRewardsPerToken, delegatorRewardsPerTokenDelta);
}
/// Updates a delegator staking rewards state
/// @dev queries the relevant delegator and committee data from the committee contract and delegation contract
/// @dev uses _updateDelegatorStakingRewards
/// @param delegator is the delegator to update
function updateDelegatorStakingRewards(address delegator) private {
Settings memory _settings = settings;
(, , uint totalCommitteeWeight) = committeeContract.getCommitteeStats();
StakingRewardsState memory _stakingRewardsState = _updateStakingRewardsState(totalCommitteeWeight, _settings);
(address guardian, uint delegatorStake) = delegationsContract.getDelegationInfo(delegator);
GuardianStakingRewards memory guardianRewards = updateGuardianStakingRewards(guardian, _stakingRewardsState, _settings);
_updateDelegatorStakingRewards(delegator, delegatorStake, guardian, guardianRewards);
}
// Guardian settings
/// Returns the guardian's delegator portion in percent-mille
/// @dev if no explicit value was set by the guardian returns the default value
/// @dev enforces the maximum delegators staking rewards cut
function _getGuardianDelegatorsStakingRewardsPercentMille(address guardian, Settings memory _settings) private view returns (uint256 delegatorRewardsRatioPercentMille) {
GuardianRewardSettings memory guardianSettings = guardiansRewardSettings[guardian];
delegatorRewardsRatioPercentMille = guardianSettings.overrideDefault ? guardianSettings.delegatorsStakingRewardsPercentMille : _settings.defaultDelegatorsStakingRewardsPercentMille;
return Math.min(delegatorRewardsRatioPercentMille, _settings.maxDelegatorsStakingRewardsPercentMille);
}
/// Migrates a list of guardians' delegators portion setting from a previous staking rewards contract
/// @dev called by the constructor
function migrateGuardiansSettings(IStakingRewards previousRewardsContract, address[] memory guardiansToMigrate) private {
for (uint i = 0; i < guardiansToMigrate.length; i++) {
_setGuardianDelegatorsStakingRewardsPercentMille(guardiansToMigrate[i], uint32(previousRewardsContract.getGuardianDelegatorsStakingRewardsPercentMille(guardiansToMigrate[i])));
}
}
// Governance and misc.
/// Sets the annual rate and cap for the staking reward
/// @param annualRateInPercentMille is the annual rate in percent-mille
/// @param annualCap is the annual staking rewards cap
function _setAnnualStakingRewardsRate(uint32 annualRateInPercentMille, uint96 annualCap) private {
Settings memory _settings = settings;
_settings.annualRateInPercentMille = annualRateInPercentMille;
_settings.annualCap = annualCap;
settings = _settings;
emit AnnualStakingRewardsRateChanged(annualRateInPercentMille, annualCap);
}
/// Sets the guardian's delegators staking reward portion
/// @param guardian is the guardian to set
/// @param delegatorRewardsPercentMille is the delegators portion in percent-mille (0 - maxDelegatorsStakingRewardsPercentMille)
function _setGuardianDelegatorsStakingRewardsPercentMille(address guardian, uint32 delegatorRewardsPercentMille) private {
guardiansRewardSettings[guardian] = GuardianRewardSettings({
overrideDefault: true,
delegatorsStakingRewardsPercentMille: delegatorRewardsPercentMille
});
emit GuardianDelegatorsStakingRewardsPercentMilleUpdated(guardian, delegatorRewardsPercentMille);
}
/// Claims an addr staking rewards and update its rewards state without transferring the rewards
/// @dev used by claimStakingRewards and migrateRewardsBalance
/// @param addr is the address to claim rewards for
/// @return guardianRewards is the claimed guardian rewards balance
/// @return delegatorRewards is the claimed delegator rewards balance
function claimStakingRewardsLocally(address addr) private returns (uint256 guardianRewards, uint256 delegatorRewards) {
updateDelegatorStakingRewards(addr);
guardianRewards = guardiansStakingRewards[addr].balance;
guardiansStakingRewards[addr].balance = 0;
delegatorRewards = delegatorsStakingRewards[addr].balance;
delegatorsStakingRewards[addr].balance = 0;
uint256 total = delegatorRewards.add(guardianRewards);
StakingRewardsState memory _stakingRewardsState = stakingRewardsState;
uint256 _stakingRewardsContractBalance = stakingRewardsContractBalance;
if (total > _stakingRewardsContractBalance) {
_stakingRewardsContractBalance = withdrawRewardsWalletAllocatedTokens(_stakingRewardsState);
}
stakingRewardsContractBalance = _stakingRewardsContractBalance.sub(total);
stakingRewardsState.unclaimedStakingRewards = _stakingRewardsState.unclaimedStakingRewards.sub(total);
}
/// Withdraws the tokens that were allocated to the contract from the staking rewards wallet
/// @dev used as part of the migration flow to withdraw all the funds allocated for participants before updating the wallet client to a new contract
/// @param _stakingRewardsState is the updated global staking rewards state
function withdrawRewardsWalletAllocatedTokens(StakingRewardsState memory _stakingRewardsState) private returns (uint256 _stakingRewardsContractBalance){
_stakingRewardsContractBalance = stakingRewardsContractBalance;
uint256 allocated = _stakingRewardsState.unclaimedStakingRewards.sub(_stakingRewardsContractBalance);
stakingRewardsWallet.withdraw(allocated);
_stakingRewardsContractBalance = _stakingRewardsContractBalance.add(allocated);
stakingRewardsContractBalance = _stakingRewardsContractBalance;
}
/*
* Contracts topology / registry interface
*/
ICommittee committeeContract;
IDelegations delegationsContract;
IProtocolWallet stakingRewardsWallet;
IStakingContract stakingContract;
/// Refreshes the address of the other contracts the contract interacts with
/// @dev called by the registry contract upon an update of a contract in the registry
function refreshContracts() external override {
committeeContract = ICommittee(getCommitteeContract());
delegationsContract = IDelegations(getDelegationsContract());
stakingRewardsWallet = IProtocolWallet(getStakingRewardsWallet());
stakingContract = IStakingContract(getStakingContract());
}
} | @title Protocol Wallet interface | interface IProtocolWallet {
event FundsAddedToPool(uint256 added, uint256 total);
function getBalance() external view returns (uint256 balance);
function topUp(uint256 amount) external;
function withdraw(uint256 amount) external; /* onlyClient */
event ClientSet(address client);
event MaxAnnualRateSet(uint256 maxAnnualRate);
event EmergencyWithdrawal(address addr, address token);
event OutstandingTokensReset(uint256 startTime);
function setMaxAnnualRate(uint256 _annualRate) external; /* onlyMigrationOwner */
function getMaxAnnualRate() external view returns (uint256);
function resetOutstandingTokens(uint256 startTime) external; /* onlyMigrationOwner */
function emergencyWithdraw(address erc20) external; /* onlyMigrationOwner */
function setClient(address _client) external; /* onlyFunctionalOwner */
}
}
| 450,078 | [
1,
5752,
20126,
1560,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
5752,
16936,
288,
203,
565,
871,
478,
19156,
8602,
774,
2864,
12,
11890,
5034,
3096,
16,
2254,
5034,
2078,
1769,
203,
203,
203,
565,
445,
2882,
6112,
1435,
3903,
1476,
1135,
261,
11890,
5034,
11013,
1769,
203,
203,
565,
445,
1760,
1211,
12,
11890,
5034,
3844,
13,
3903,
31,
203,
203,
565,
445,
598,
9446,
12,
11890,
5034,
3844,
13,
3903,
31,
1748,
1338,
1227,
1195,
203,
203,
203,
203,
565,
871,
2445,
694,
12,
2867,
1004,
1769,
203,
565,
871,
4238,
14694,
1462,
4727,
694,
12,
11890,
5034,
943,
14694,
1462,
4727,
1769,
203,
565,
871,
512,
6592,
75,
2075,
1190,
9446,
287,
12,
2867,
3091,
16,
1758,
1147,
1769,
203,
565,
871,
2976,
15167,
5157,
7013,
12,
11890,
5034,
8657,
1769,
203,
203,
565,
445,
10851,
14694,
1462,
4727,
12,
11890,
5034,
389,
1072,
1462,
4727,
13,
3903,
31,
1748,
1338,
10224,
5541,
1195,
203,
203,
565,
445,
7288,
14694,
1462,
4727,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
2715,
1182,
15167,
5157,
12,
11890,
5034,
8657,
13,
3903,
31,
1748,
1338,
10224,
5541,
1195,
203,
203,
565,
445,
801,
24530,
1190,
9446,
12,
2867,
6445,
71,
3462,
13,
3903,
31,
1748,
1338,
10224,
5541,
1195,
203,
203,
565,
445,
26001,
12,
2867,
389,
2625,
13,
3903,
31,
1748,
1338,
2083,
287,
5541,
1195,
203,
203,
97,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/// @title The external contract that is responsible for generating metadata for the kitties,
/// it has one function that will return the data as bytes.
contract ERC721Metadata {
/// @dev Given a token Id, returns a byte array that is supposed to be converted into string.
function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) {
if (_tokenId == 1) {
buffer[0] = "Hello World! :D";
count = 15;
} else if (_tokenId == 2) {
buffer[0] = "I would definitely choose a medi";
buffer[1] = "um length string.";
count = 49;
} else if (_tokenId == 3) {
buffer[0] = "Lorem ipsum dolor sit amet, mi e";
buffer[1] = "st accumsan dapibus augue lorem,";
buffer[2] = " tristique vestibulum id, libero";
buffer[3] = " suscipit varius sapien aliquam.";
count = 128;
}
}
}
| Required methods Events Optional function name() public view returns (string name); function symbol() public view returns (string symbol); function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); ERC-165 Compatibility (https:github.com/ethereum/EIPs/issues/165) | contract ERC721 {
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
| 942,140 | [
1,
3705,
2590,
9043,
4055,
445,
508,
1435,
1071,
1476,
1135,
261,
1080,
508,
1769,
445,
3273,
1435,
1071,
1476,
1135,
261,
1080,
3273,
1769,
445,
2430,
951,
5541,
12,
2867,
389,
8443,
13,
3903,
1476,
1135,
261,
11890,
5034,
8526,
1147,
2673,
1769,
445,
1147,
2277,
12,
11890,
5034,
389,
2316,
548,
16,
533,
389,
23616,
6568,
13,
1071,
1476,
1135,
261,
1080,
1123,
1489,
1769,
4232,
39,
17,
28275,
5427,
270,
3628,
261,
4528,
30,
6662,
18,
832,
19,
546,
822,
379,
19,
41,
18246,
19,
9618,
19,
28275,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4232,
39,
27,
5340,
288,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
5034,
2078,
1769,
203,
565,
445,
11013,
951,
12,
2867,
389,
8443,
13,
1071,
1476,
1135,
261,
11890,
5034,
11013,
1769,
203,
565,
445,
3410,
951,
12,
11890,
5034,
389,
2316,
548,
13,
3903,
1476,
1135,
261,
2867,
3410,
1769,
203,
565,
445,
6617,
537,
12,
2867,
389,
869,
16,
2254,
5034,
389,
2316,
548,
13,
3903,
31,
203,
565,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
2316,
548,
13,
3903,
31,
203,
565,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
2316,
548,
13,
3903,
31,
203,
203,
565,
871,
12279,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
1147,
548,
1769,
203,
565,
871,
1716,
685,
1125,
12,
2867,
3410,
16,
1758,
20412,
16,
2254,
5034,
1147,
548,
1769,
203,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
389,
5831,
734,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "./events.sol";
import "../../../../infiniteProxy/IProxy.sol";
contract RebalancerModule is Events {
using SafeERC20 for IERC20;
/**
* @dev Only rebalancer gaurd.
*/
modifier onlyRebalancer() {
require(
_isRebalancer[msg.sender] ||
IProxy(address(this)).getAdmin() == msg.sender,
"only rebalancer"
);
_;
}
/**
* @dev low gas function just to collect profit.
* @notice Collected the profit & leave it in the DSA itself to optimize further on gas.
*/
function collectProfit(
bool isWeth, // either weth or steth
uint256 withdrawAmt_,
uint256 amt_,
uint256 unitAmt_,
bytes memory oneInchData_
) external nonReentrant onlyRebalancer {
uint256 profits_ = getNewProfits();
require(amt_ <= profits_, "amount-exceeds-profit");
uint256 length_ = 1;
if (withdrawAmt_ > 0) length_++;
string[] memory targets_ = new string[](length_);
bytes[] memory calldata_ = new bytes[](length_);
address sellToken_ = isWeth
? address(wethContract)
: address(stethContract);
uint256 maxAmt_ = (getStethCollateralAmount() * _idealExcessAmt) /
10000;
if (withdrawAmt_ > 0) {
if (isWeth) {
targets_[0] = "AAVE-V2-A";
calldata_[0] = abi.encodeWithSignature(
"borrow(address,uint256,uint256,uint256,uint256)",
address(wethContract),
withdrawAmt_,
2,
0,
0
);
} else {
targets_[0] = "AAVE-V2-A";
calldata_[0] = abi.encodeWithSignature(
"withdraw(address,uint256,uint256,uint256)",
address(stethContract),
withdrawAmt_,
0,
0
);
}
}
targets_[length_ - 1] = "1INCH-A";
calldata_[length_ - 1] = abi.encodeWithSignature(
"sell(address,address,uint256,uint256,bytes,uint256)",
_token,
sellToken_,
amt_,
unitAmt_,
oneInchData_,
0
);
_vaultDsa.cast(targets_, calldata_, address(this));
if (withdrawAmt_ > 0)
require(
IERC20(sellToken_).balanceOf(address(_vaultDsa)) <= maxAmt_,
"withdrawal-exceeds-max-limit"
);
emit collectProfitLog(isWeth, withdrawAmt_, amt_, unitAmt_);
}
struct RebalanceOneVariables {
bool isOk;
uint256 i;
uint256 j;
uint256 length;
string[] targets;
bytes[] calldatas;
bool criticalIsOk;
bool minIsOk;
}
/**
* @dev Rebalancer function to leverage and rebalance the position.
*/
function rebalanceOne(
address flashTkn_,
uint256 flashAmt_,
uint256 route_,
address[] memory vaults_, // leverage using other vaults
uint256[] memory amts_,
uint256 leverageAmt_,
uint256 swapAmt_, // 1inch's swap amount
uint256 tokenSupplyAmt_,
uint256 tokenWithdrawAmt_,
uint256 unitAmt_,
bytes memory oneInchData_
) external nonReentrant onlyRebalancer {
if (leverageAmt_ < 1e14) leverageAmt_ = 0;
if (tokenWithdrawAmt_ < _tokenMinLimit) tokenWithdrawAmt_ = 0;
if (tokenSupplyAmt_ >= _tokenMinLimit)
_token.safeTransfer(address(_vaultDsa), tokenSupplyAmt_);
RebalanceOneVariables memory v_;
v_.isOk = validateLeverageAmt(vaults_, amts_, leverageAmt_, swapAmt_);
require(v_.isOk, "swap-amounts-are-not-proper");
v_.length = amts_.length;
uint256 tokenDsaBal_ = _token.balanceOf(address(_vaultDsa));
if (tokenDsaBal_ >= _tokenMinLimit) v_.j += 1;
if (leverageAmt_ > 0) v_.j += 1;
if (flashAmt_ > 0) v_.j += 3;
if (swapAmt_ > 0) v_.j += 2; // only deposit stEth in Aave if swap amt > 0.
if (v_.length > 0) v_.j += v_.length;
if (tokenWithdrawAmt_ > 0) v_.j += 2;
v_.targets = new string[](v_.j);
v_.calldatas = new bytes[](v_.j);
if (tokenDsaBal_ >= _tokenMinLimit) {
v_.targets[v_.i] = "AAVE-V2-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"deposit(address,uint256,uint256,uint256)",
address(_token),
type(uint256).max,
0,
0
);
v_.i++;
}
if (leverageAmt_ > 0) {
if (flashAmt_ > 0) {
v_.targets[v_.i] = "AAVE-V2-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"deposit(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
v_.i++;
}
v_.targets[v_.i] = "AAVE-V2-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"borrow(address,uint256,uint256,uint256,uint256)",
address(wethContract),
leverageAmt_,
2,
0,
0
);
v_.i++;
// Doing swaps from different vaults using deleverage to reduce other vaults riskiness if needed.
// It takes WETH from vault and gives astETH at 1:1
for (uint256 k = 0; k < v_.length; k++) {
v_.targets[v_.i] = "LITE-A"; // Instadapp Lite vaults connector
v_.calldatas[v_.i] = abi.encodeWithSignature(
"deleverage(address,uint256,uint256,uint256)",
vaults_[k],
amts_[k],
0,
0
);
v_.i++;
}
if (swapAmt_ > 0) {
require(unitAmt_ > (1e18 - 10), "invalid-unit-amt");
v_.targets[v_.i] = "1INCH-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"sell(address,address,uint256,uint256,bytes,uint256)",
address(stethContract),
address(wethContract),
swapAmt_,
unitAmt_,
oneInchData_,
0
);
v_.targets[v_.i + 1] = "AAVE-V2-A";
v_.calldatas[v_.i + 1] = abi.encodeWithSignature(
"deposit(address,uint256,uint256,uint256)",
address(stethContract),
type(uint256).max,
0,
0
);
v_.i += 2;
}
if (flashAmt_ > 0) {
v_.targets[v_.i] = "AAVE-V2-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"withdraw(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
v_.targets[v_.i + 1] = "INSTAPOOL-C";
v_.calldatas[v_.i + 1] = abi.encodeWithSignature(
"flashPayback(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
v_.i += 2;
}
}
if (tokenWithdrawAmt_ > 0) {
v_.targets[v_.i] = "AAVE-V2-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"withdraw(address,uint256,uint256,uint256)",
_token,
tokenWithdrawAmt_,
0,
0
);
v_.targets[v_.i + 1] = "BASIC-A";
v_.calldatas[v_.i + 1] = abi.encodeWithSignature(
"withdraw(address,uint256,address,uint256,uint256)",
_token,
tokenWithdrawAmt_,
address(this),
0,
0
);
v_.i += 2;
}
if (flashAmt_ > 0) {
bytes memory encodedFlashData_ = abi.encode(
v_.targets,
v_.calldatas
);
string[] memory flashTarget_ = new string[](1);
bytes[] memory flashCalldata_ = new bytes[](1);
flashTarget_[0] = "INSTAPOOL-C";
flashCalldata_[0] = abi.encodeWithSignature(
"flashBorrowAndCast(address,uint256,uint256,bytes,bytes)",
flashTkn_,
flashAmt_,
route_,
encodedFlashData_,
"0x"
);
_vaultDsa.cast(flashTarget_, flashCalldata_, address(this));
} else {
if (v_.j > 0)
_vaultDsa.cast(v_.targets, v_.calldatas, address(this));
}
if (leverageAmt_ > 0)
require(
getWethBorrowRate() < _ratios.maxBorrowRate,
"high-borrow-rate"
);
(v_.criticalIsOk, , v_.minIsOk, ) = validateFinalPosition();
// this will allow auth to take position to max safe limit. Only have to execute when there's a need to make other vaults safer.
if (IProxy(address(this)).getAdmin() == msg.sender) {
if (leverageAmt_ > 0)
require(v_.criticalIsOk, "aave position risky");
} else {
if (leverageAmt_ > 0)
require(v_.minIsOk, "position risky after leverage");
if (tokenWithdrawAmt_ > 0)
require(v_.criticalIsOk, "aave position risky");
}
emit rebalanceOneLog(
flashTkn_,
flashAmt_,
route_,
vaults_,
amts_,
leverageAmt_,
swapAmt_,
tokenSupplyAmt_,
tokenWithdrawAmt_,
unitAmt_
);
}
/**
* @dev Rebalancer function for saving. To be run in times of making position less risky or to fill up the withdraw amount for users to exit
*/
function rebalanceTwo(
address flashTkn_,
uint256 flashAmt_,
uint256 route_,
uint256 saveAmt_,
uint256 tokenSupplyAmt_,
uint256 unitAmt_,
bytes memory oneInchData_
) external nonReentrant onlyRebalancer {
require(unitAmt_ > (1e18 - _saveSlippage), "excess-slippage"); // TODO: set variable to update slippage? Here's it's 0.1% slippage.
uint256 i;
uint256 j;
if (tokenSupplyAmt_ >= _tokenMinLimit)
_token.safeTransfer(address(_vaultDsa), tokenSupplyAmt_);
uint256 tokenDsaBal_ = _token.balanceOf(address(_vaultDsa));
if (tokenDsaBal_ >= _tokenMinLimit) j += 1;
if (saveAmt_ > 0) j += 3;
if (flashAmt_ > 0) j += 3;
string[] memory targets_ = new string[](j);
bytes[] memory calldata_ = new bytes[](j);
if (tokenDsaBal_ >= _tokenMinLimit) {
targets_[i] = "AAVE-V2-A";
calldata_[i] = abi.encodeWithSignature(
"deposit(address,uint256,uint256,uint256)",
address(_token),
type(uint256).max,
0,
0
);
i++;
}
if (saveAmt_ > 0) {
if (flashAmt_ > 0) {
targets_[i] = "AAVE-V2-A";
calldata_[i] = abi.encodeWithSignature(
"deposit(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
i++;
}
targets_[i] = "AAVE-V2-A";
calldata_[i] = abi.encodeWithSignature(
"withdraw(address,uint256,uint256,uint256)",
address(stethContract),
saveAmt_,
0,
0
);
targets_[i + 1] = "1INCH-A";
calldata_[i + 1] = abi.encodeWithSignature(
"sell(address,address,uint256,uint256,bytes,uint256)",
address(wethContract),
address(stethContract),
saveAmt_,
unitAmt_,
oneInchData_,
1 // setId 1
);
targets_[i + 2] = "AAVE-V2-A";
calldata_[i + 2] = abi.encodeWithSignature(
"payback(address,uint256,uint256,uint256,uint256)",
address(wethContract),
0,
2,
1, // getId 1 to get the payback amount
0
);
if (flashAmt_ > 0) {
targets_[i + 3] = "AAVE-V2-A";
calldata_[i + 3] = abi.encodeWithSignature(
"withdraw(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
targets_[i + 4] = "INSTAPOOL-C";
calldata_[i + 4] = abi.encodeWithSignature(
"flashPayback(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
}
}
if (flashAmt_ > 0) {
bytes memory encodedFlashData_ = abi.encode(targets_, calldata_);
string[] memory flashTarget_ = new string[](1);
bytes[] memory flashCalldata_ = new bytes[](1);
flashTarget_[0] = "INSTAPOOL-C";
flashCalldata_[0] = abi.encodeWithSignature(
"flashBorrowAndCast(address,uint256,uint256,bytes,bytes)",
flashTkn_,
flashAmt_,
route_,
encodedFlashData_,
"0x"
);
_vaultDsa.cast(flashTarget_, flashCalldata_, address(this));
} else {
if (j > 0) _vaultDsa.cast(targets_, calldata_, address(this));
}
(, bool isOk_, , ) = validateFinalPosition();
require(isOk_, "position-risky");
emit rebalanceTwoLog(flashTkn_, flashAmt_, route_, saveAmt_, unitAmt_);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "../common/helpers.sol";
contract Events is Helpers {
event collectProfitLog(
bool isWeth,
uint256 withdrawAmt_,
uint256 amt_,
uint256 unitAmt_
);
event rebalanceOneLog(
address flashTkn_,
uint256 flashAmt_,
uint256 route_,
address[] vaults_,
uint256[] amts_,
uint256 leverageAmt_,
uint256 swapAmt_,
uint256 tokenSupplyAmt_,
uint256 tokenWithdrawAmt_,
uint256 unitAmt_
);
event rebalanceTwoLog(
address flashTkn_,
uint256 flashAmt_,
uint256 route_,
uint256 saveAmt_,
uint256 unitAmt_
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IProxy {
function getAdmin() external view returns (address);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "./variables.sol";
contract Helpers is Variables {
/**
* @dev reentrancy gaurd.
*/
modifier nonReentrant() {
require(_status != 2, "ReentrancyGuard: reentrant call");
_status = 2;
_;
_status = 1;
}
/**
* @dev Helper function to get current eth borrow rate on aave.
*/
function getWethBorrowRate()
internal
view
returns (uint256 wethBorrowRate_)
{
(, , , , wethBorrowRate_, , , , , ) = aaveProtocolDataProvider
.getReserveData(address(wethContract));
}
/**
* @dev Helper function to get current token collateral on aave.
*/
function getTokenCollateralAmount()
internal
view
returns (uint256 tokenAmount_)
{
tokenAmount_ = _atoken.balanceOf(address(_vaultDsa));
}
/**
* @dev Helper function to get current steth collateral on aave.
*/
function getStethCollateralAmount()
internal
view
returns (uint256 stEthAmount_)
{
stEthAmount_ = astethToken.balanceOf(address(_vaultDsa));
}
/**
* @dev Helper function to get current eth debt on aave.
*/
function getWethDebtAmount()
internal
view
returns (uint256 wethDebtAmount_)
{
wethDebtAmount_ = awethVariableDebtToken.balanceOf(address(_vaultDsa));
}
/**
* @dev Helper function to token balances of everywhere.
*/
function getVaultBalances()
public
view
returns (
uint256 tokenCollateralAmt_,
uint256 stethCollateralAmt_,
uint256 wethDebtAmt_,
uint256 tokenVaultBal_,
uint256 tokenDSABal_,
uint256 netTokenBal_
)
{
tokenCollateralAmt_ = getTokenCollateralAmount();
stethCollateralAmt_ = getStethCollateralAmount();
wethDebtAmt_ = getWethDebtAmount();
tokenVaultBal_ = _token.balanceOf(address(this));
tokenDSABal_ = _token.balanceOf(address(_vaultDsa));
netTokenBal_ = tokenCollateralAmt_ + tokenVaultBal_ + tokenDSABal_;
}
// returns net eth. net stETH + ETH - net ETH debt.
function getNewProfits() public view returns (uint256 profits_) {
uint256 stEthCol_ = getStethCollateralAmount();
uint256 stEthDsaBal_ = stethContract.balanceOf(address(_vaultDsa));
uint256 wethDsaBal_ = wethContract.balanceOf(address(_vaultDsa));
uint256 positiveEth_ = stEthCol_ + stEthDsaBal_ + wethDsaBal_;
uint256 negativeEth_ = getWethDebtAmount() + _revenueEth;
profits_ = negativeEth_ < positiveEth_
? positiveEth_ - negativeEth_
: 0;
}
/**
* @dev Helper function to get current exchange price and new revenue generated.
*/
function getCurrentExchangePrice()
public
view
returns (uint256 exchangePrice_, uint256 newTokenRevenue_)
{
// net token balance is total balance. stETH collateral & ETH debt cancels out each other.
(, , , , , uint256 netTokenBalance_) = getVaultBalances();
netTokenBalance_ -= _revenue;
uint256 totalSupply_ = totalSupply();
uint256 exchangePriceWithRevenue_;
if (totalSupply_ != 0) {
exchangePriceWithRevenue_ =
(netTokenBalance_ * 1e18) /
totalSupply_;
} else {
exchangePriceWithRevenue_ = 1e18;
}
// Only calculate revenue if there's a profit
if (exchangePriceWithRevenue_ > _lastRevenueExchangePrice) {
uint256 newProfit_ = netTokenBalance_ -
((_lastRevenueExchangePrice * totalSupply_) / 1e18);
newTokenRevenue_ = (newProfit_ * _revenueFee) / 10000;
exchangePrice_ =
((netTokenBalance_ - newTokenRevenue_) * 1e18) /
totalSupply_;
} else {
exchangePrice_ = exchangePriceWithRevenue_;
}
}
struct ValidateFinalPosition {
uint256 tokenPriceInBaseCurrency;
uint256 ethPriceInBaseCurrency;
uint256 excessDebtInBaseCurrency;
uint256 netTokenColInBaseCurrency;
uint256 netTokenSupplyInBaseCurrency;
uint256 ratioMax;
uint256 ratioMin;
}
/**
* @dev Helper function to validate the safety of aave position after rebalancing.
*/
function validateFinalPosition()
internal
view
returns (
bool criticalIsOk_,
bool criticalGapIsOk_,
bool minIsOk_,
bool minGapIsOk_
)
{
(
uint256 tokenColAmt_,
uint256 stethColAmt_,
uint256 wethDebt_,
,
,
uint256 netTokenBal_
) = getVaultBalances();
uint256 ethCoveringDebt_ = (stethColAmt_ * _ratios.stEthLimit) / 10000;
uint256 excessDebt_ = ethCoveringDebt_ < wethDebt_
? wethDebt_ - ethCoveringDebt_
: 0;
if (excessDebt_ > 0) {
IAavePriceOracle aaveOracle_ = IAavePriceOracle(
aaveAddressProvider.getPriceOracle()
);
ValidateFinalPosition memory validateFinalPosition_;
validateFinalPosition_.tokenPriceInBaseCurrency = aaveOracle_
.getAssetPrice(address(_token));
validateFinalPosition_.ethPriceInBaseCurrency = aaveOracle_
.getAssetPrice(address(wethContract));
validateFinalPosition_.excessDebtInBaseCurrency =
(excessDebt_ * validateFinalPosition_.ethPriceInBaseCurrency) /
1e18;
validateFinalPosition_.netTokenColInBaseCurrency =
(tokenColAmt_ *
validateFinalPosition_.tokenPriceInBaseCurrency) /
(10**_tokenDecimals);
validateFinalPosition_.netTokenSupplyInBaseCurrency =
(netTokenBal_ *
validateFinalPosition_.tokenPriceInBaseCurrency) /
(10**_tokenDecimals);
validateFinalPosition_.ratioMax =
(validateFinalPosition_.excessDebtInBaseCurrency * 10000) /
validateFinalPosition_.netTokenColInBaseCurrency;
validateFinalPosition_.ratioMin =
(validateFinalPosition_.excessDebtInBaseCurrency * 10000) /
validateFinalPosition_.netTokenSupplyInBaseCurrency;
criticalIsOk_ = validateFinalPosition_.ratioMax < _ratios.maxLimit;
criticalGapIsOk_ =
validateFinalPosition_.ratioMax > _ratios.maxLimitGap;
minIsOk_ = validateFinalPosition_.ratioMin < _ratios.minLimit;
minGapIsOk_ = validateFinalPosition_.ratioMin > _ratios.minLimitGap;
} else {
criticalIsOk_ = true;
minIsOk_ = true;
}
}
/**
* @dev Helper function to validate if the leverage amount is divided correctly amount other-vault-swaps and 1inch-swap .
*/
function validateLeverageAmt(
address[] memory vaults_,
uint256[] memory amts_,
uint256 leverageAmt_,
uint256 swapAmt_
) internal pure returns (bool isOk_) {
uint256 l_ = vaults_.length;
isOk_ = l_ == amts_.length;
if (isOk_) {
uint256 totalAmt_ = swapAmt_;
for (uint256 i = 0; i < l_; i++) {
totalAmt_ = totalAmt_ + amts_[i];
}
isOk_ = totalAmt_ <= leverageAmt_; // total amount should not be more than leverage amount
isOk_ = isOk_ && ((leverageAmt_ * 9999) / 10000) < totalAmt_; // total amount should be more than (0.9999 * leverage amount). 0.01% slippage gap.
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "./interfaces.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
contract ConstantVariables is ERC20Upgradeable {
IInstaIndex internal constant instaIndex =
IInstaIndex(0x2971AdFa57b20E5a416aE5a708A8655A9c74f723);
IERC20 internal constant wethContract = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IERC20 internal constant stethContract = IERC20(0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84);
IAaveProtocolDataProvider internal constant aaveProtocolDataProvider =
IAaveProtocolDataProvider(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d);
IAaveAddressProvider internal constant aaveAddressProvider =
IAaveAddressProvider(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5);
IERC20 internal constant awethVariableDebtToken =
IERC20(0xF63B34710400CAd3e044cFfDcAb00a0f32E33eCf);
IERC20 internal constant astethToken =
IERC20(0x1982b2F5814301d4e9a8b0201555376e62F82428);
IInstaList internal constant instaList =
IInstaList(0x4c8a1BEb8a87765788946D6B19C6C6355194AbEb);
}
contract Variables is ConstantVariables {
uint256 internal _status = 1;
// only authorized addresses can rebalance
mapping(address => bool) internal _isRebalancer;
IERC20 internal _token;
uint8 internal _tokenDecimals;
uint256 internal _tokenMinLimit;
IERC20 internal _atoken;
IDSA internal _vaultDsa;
struct Ratios {
uint16 maxLimit; // Above this withdrawals are not allowed
uint16 maxLimitGap;
uint16 minLimit; // After leverage the ratio should be below minLimit & above minLimitGap
uint16 minLimitGap;
uint16 stEthLimit; // if 7500. Meaning stETH collateral covers 75% of the ETH debt. Excess ETH will be covered by token limit.
// send borrow rate in 4 decimals from UI. In the smart contract it'll convert to 27 decimals which where is 100%
uint128 maxBorrowRate; // maximum borrow rate above this leveraging should not happen
}
Ratios internal _ratios;
// last revenue exchange price (helps in calculating revenue)
// Exchange price when revenue got updated last. It'll only increase overtime.
uint256 internal _lastRevenueExchangePrice;
uint256 internal _revenueFee; // 1000 = 10% (10% of user's profit)
uint256 internal _revenue;
uint256 internal _revenueEth;
uint256 internal _withdrawalFee; // 10000 = 100%
uint256 internal _idealExcessAmt; // 10 means 0.1% of total stEth/Eth supply (collateral + ideal balance)
uint256 internal _swapFee; // 5 means 0.05%. This is the fee on leverage function which allows swap of stETH -> ETH
uint256 internal _saveSlippage; // 1e16 means 1%
uint256 internal _deleverageFee; // 1 means 0.01%
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IInstaIndex {
function build(
address owner_,
uint256 accountVersion_,
address origin_
) external returns (address account_);
}
interface IDSA {
function cast(
string[] calldata _targetNames,
bytes[] calldata _datas,
address _origin
) external payable returns (bytes32);
}
interface IAaveProtocolDataProvider {
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
);
}
interface IAaveAddressProvider {
function getPriceOracle() external view returns (address);
}
interface IAavePriceOracle {
function getAssetPrice(address _asset) external view returns (uint256);
}
interface TokenInterface {
function approve(address, uint256) external;
function transfer(address, uint256) external;
function transferFrom(
address,
address,
uint256
) external;
function deposit() external payable;
function withdraw(uint256) external;
function balanceOf(address) external view returns (uint256);
function decimals() external view returns (uint256);
function totalSupply() external view returns (uint256);
}
interface IInstaList {
function accountID(address) external view returns (uint64);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `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 {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (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 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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | total amount should be more than (0.9999 * leverage amount). 0.01% slippage gap.
| isOk_ = isOk_ && ((leverageAmt_ * 9999) / 10000) < totalAmt_; | 161,543 | [
1,
4963,
3844,
1410,
506,
1898,
2353,
261,
20,
18,
7991,
225,
884,
5682,
3844,
2934,
374,
18,
1611,
9,
272,
3169,
2433,
9300,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5411,
353,
8809,
67,
273,
353,
8809,
67,
597,
14015,
298,
5682,
31787,
67,
380,
30082,
13,
342,
12619,
13,
411,
2078,
31787,
67,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x5199daE8A7Fc33B7f25C24Ff8930C6432703835f/sources/browser/GeoPreSale.sol | If amount of geos that can be purchased is higher than what is available in the contract then
| if(geoAmount > availableGeosToPurchase) { | 8,472,192 | [
1,
2047,
3844,
434,
8244,
538,
716,
848,
506,
5405,
343,
8905,
353,
10478,
2353,
4121,
353,
2319,
316,
326,
6835,
1508,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
12,
12376,
6275,
405,
2319,
18809,
538,
774,
23164,
13,
288,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.6.2;
import {IERC20, ERC20} from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import {Ownable} from "openzeppelin-solidity/contracts/access/Ownable.sol";
import {BridgedToken} from "./BridgedToken.sol";
import {RouterFactory} from "./RouterFactory.sol";
import {Observer, PubSub} from "./IPubSub.sol";
contract Gateway is Ownable,Observer {
event TokenMapReq(bytes32 indexed chainFrom, address indexed originToken, address indexed tokenReq, uint8 decimals, string name, string symbol);
bytes32 TokenMapReqEventSig = keccak256("TokenMapReq(bytes32,address,address,uint8,string,string)");
event TokenMapAck(address indexed tokenReq, address indexed tokenAck);
bytes32 TokenMapAckEventSig = keccak256("TokenMapAck(address,address)");
bytes32 ERC20TransferEventSig = keccak256("Transfer(address,address,uint256)");
address constant INVALID = address(0);
bytes32 public chainType; // other side chainType: keccak256(chainName)
address public chainGate; // other side chain gate contract address
// origin token is created in other chain
mapping(address=>BridgedToken) public RxMappedForward; // originToken => mappingToken
address[] public RxMappedList;
// origin token is created in this chain
mapping(address=>address) public TxMappedForward; // originToken => mappingToken
mapping(address=>address) public TxMappedInverse; // mappingToken => originToken
address[] public TxMappedList;
constructor(bytes32 _chainType) public {
chainType = _chainType;
}
function getMappedSize() view public returns(uint256, uint256) {
return (TxMappedList.length, RxMappedList.length);
}
function bindGate(address gate) public onlyOwner {
chainGate = gate;
GateManager manager = GateManager(owner());
manager.Subscribe(gate);
}
function onTokenMapReqEvent(bytes32 chainFrom, address srcToken, address tokenReq, uint8 decimals, string memory name, string memory symbol) private {
GateManager manager = GateManager(owner());
BridgedToken token;
if(chainFrom == chainType) {
token = manager.newMappingToken(chainFrom, srcToken, decimals, name, symbol);
}else{
token = manager.applyMappingToken(chainFrom, srcToken);
}
RxMappedForward[tokenReq] = token;
RxMappedList.push(tokenReq);
manager.Subscribe(tokenReq);
emit TokenMapAck(tokenReq, address(token));
}
function onTokenMapAckEvent(address tokenReq, address tokenAck) private {
// event TokenMapAck(address indexed tokenReq, address indexed tokenAck);
require(TxMappedForward[tokenReq] == INVALID, "impossible ack"); // just check, shouldn't happen
TxMappedForward[tokenReq] = tokenAck;
TxMappedInverse[tokenAck] = tokenReq;
TxMappedList.push(tokenReq);
GateManager manager = GateManager(owner());
manager.Subscribe(tokenAck);
}
function mapToken(ERC20 token) public {
GateManager manager = GateManager(owner());
(bytes32 chainFrom, address originToken) = manager.getTokenInfo(address(token));
if(chainFrom == bytes32(0)) {
chainFrom = manager.chainType();
originToken = address(token);
}
address tokenReq = address(token);
//require(chainFrom != chainType, "recursion mapping");
require(TxMappedForward[tokenReq] == INVALID, "already mapped");
uint8 decimals = token.decimals();
string memory name = token.name();
string memory symbol = token.symbol();
emit TokenMapReq(chainFrom, originToken, tokenReq, decimals, name, symbol);
}
// ...
function onEvent(address publisher, bytes32[] memory topics, bytes memory data) public override {
GateManager manager = GateManager(owner());
PubSub router = manager.GateRouter(chainType);
require(address(router) == msg.sender, "onlyRouter");
bytes32 eventSig = topics[0];
if (publisher == chainGate) {
if (eventSig == TokenMapReqEventSig) {
//TokenMapReq(bytes32 indexed chainFrom, address indexed originToken, address indexed tokenReq, uint8 decimals, string name, string symbol);
bytes32 chainFrom = topics[1];
address originToken = address(uint160(uint256(topics[2])));
address tokenReq = address(uint160(uint256(topics[3])));
(uint8 decimals, string memory name, string memory symbol) = abi.decode(data, (uint8, string, string));
onTokenMapReqEvent(chainFrom, originToken, tokenReq, decimals, name, symbol);
} else if (eventSig == TokenMapAckEventSig) {
address tokenReq = address(uint160(uint256(topics[1])));
address tokenAck = address(uint160(uint256(topics[2])));
onTokenMapAckEvent(tokenReq, tokenAck);
}
return;
}
BridgedToken token = RxMappedForward[publisher];
address to = address(uint160(uint256(topics[2])));
require(to == chainGate, "not to gate");
address from = address(uint160(uint256(topics[1])));
uint256 value = abi.decode(data, (uint256));
if(address(token) != INVALID){ // RxMapped token
token.mint(from, value);
return;
}
token = BridgedToken(TxMappedInverse[publisher]); // TxMapped token; should be ERC2O
require(address(token) != INVALID, "UNKONW TOKEN");
if(token.balanceOf(address(this)) < value) {
manager.transfer(token, from, value); // fee?
}else{
token.transfer(from, value);
}
}
function trasnfer(IERC20 token, address to, uint256 amount) public onlyOwner {
token.transfer(to, amount);
}
}
contract GateManager is Ownable,Observer {
address constant INVALID = address(0);
event newGate(address indexed gate);
bytes32 constant newGateSig = keccak256("newGate(address)");
struct TokenInfo {
bytes32 chainType;
address token;
}
RouterFactory public factory; // constant
mapping(bytes32=>Gateway) public GateMap; // chainType => Gateway
mapping(address=>bytes32) public GateMapInv; // Gateway => chainType
Gateway[] public Gates;
mapping(bytes32=>address) public GateManagers;
mapping(address=>bytes32) public GateRouterInv; // PubSub => chainType
mapping(bytes32=>PubSub) public GateRouter; // chainType => PubSub
mapping(address=>TokenInfo) public TokenFrom;
bytes32 public chainType;
string public chainName;
constructor(RouterFactory _factory, string memory _chainName) public {
factory = _factory;
chainName = _chainName;
chainType = keccak256(bytes(_chainName));
}
modifier onlyGate() {require(GateMapInv[msg.sender] != bytes32(0), "onlyGate");_;}
function getTokenInfo(address token) public view returns(bytes32, address) {
TokenInfo storage info = TokenFrom[token];
return (info.chainType, info.token);
}
function GateSize() public view returns(uint256) {
return Gates.length;
}
function transfer(IERC20 token, address to, uint256 amount) public onlyGate {
for(uint256 i = 0; amount > 0 && i < Gates.length; i++) {
Gateway gate = Gates[i];
uint256 balance = token.balanceOf(address(gate));
if(balance == 0) continue;
if(balance > amount)
balance = amount;
gate.trasnfer(token, to, balance);
amount -= balance;
}
require(amount == 0, "impossible amount!");
}
function newMappingToken(bytes32 _chainType, address srcToken,
uint8 decimals, string memory name, string memory symbol)onlyGate public returns(BridgedToken) {
bytes32 salt = bytes32(uint256(_chainType)^uint160(srcToken));
BridgedToken token = new BridgedToken{salt: salt}(name, symbol, decimals); // apporve mintable
token.grantRole(token.MINTER_ROLE(), msg.sender);
TokenFrom[address(token)] = TokenInfo(_chainType, srcToken);
return token;
}
function applyMappingToken(bytes32 _chainType, address srcToken) onlyGate public returns(BridgedToken) {
BridgedToken token = GateMap[_chainType].RxMappedForward(srcToken); // approve mintable
token.grantRole(token.MINTER_ROLE(), msg.sender);
return token;
}
function createGate(bytes32 _chainType) private {
Gateway gate = new Gateway{salt:_chainType}(_chainType);
emit newGate(address(gate));
GateMap[_chainType] = gate;
GateMapInv[address(gate)] = _chainType;
Gates.push(gate);
PubSub router = factory.createRouter(_chainType);
GateRouter[_chainType] = router;
GateRouterInv[address(router)] = _chainType;
}
function bindGateManager(bytes32 _chainType, address gateManager) public onlyOwner {
GateManagers[_chainType] = gateManager;
createGate(_chainType);
PubSub router = GateRouter[_chainType];
router.Subscribe(gateManager, this);
}
function onEvent(address publisher, bytes32[] memory topics, bytes memory data) public override {
bytes32 _chainType = GateRouterInv[msg.sender]; // onlyRouter
require(publisher == GateManagers[_chainType], "onlyRouter");
if(topics[0] == newGateSig){
Gateway gate = GateMap[_chainType];
address bindGate = address(uint160(uint256(topics[1])));
gate.bindGate(bindGate);
}
data;
}
function Subscribe(address from) public onlyGate {
bytes32 _chainType = GateMapInv[msg.sender];
PubSub router = GateRouter[_chainType];
router.Subscribe(from, Observer(msg.sender));
}
}
| mappingToken => originToken
| mapping(address=>address) public TxMappedInverse; | 15,807,689 | [
1,
6770,
1345,
516,
4026,
1345,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
2867,
9207,
2867,
13,
1071,
6424,
12868,
16376,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "hardhat/console.sol";
contract Presale is ReentrancyGuard, Ownable {
uint256 public constant DECIMALS = 18;
uint256 public constant DENOMINATOR = 10**DECIMALS;
uint256 public constant INITIAL_PRICE = (DENOMINATOR) / 7402; //Initial price 1 ETH == 7402 tokens
/**
* @dev price must be set with `DENOMINATOR` decimals
*/
uint256 public price = INITIAL_PRICE;
address payable public receiverOfEarnings;
IERC20Metadata public presaleToken;
uint8 internal tokenDecimals;
bool public paused;
event PriceChange(uint256 oldPrice, uint256 newPrice);
event BoughtWithBNB(uint256 amount);
/**
* @dev Throws is the presale is paused
*/
modifier notPaused() {
require(!paused, "Presale is paused");
_;
}
/**
* @dev Throws is presale is NOT paused
*/
modifier isPaused() {
require(paused, "Presale is not paused");
_;
}
/**
* @param _presaleToken adress of the token to be purchased through preslae
* @param _receiverOfEarnings address of the wallet to be allowed to withdraw the proceeds
*/
constructor(
address _presaleToken,
address payable _receiverOfEarnings
) {
require(
_receiverOfEarnings != address(0),
"Receiver wallet cannot be 0"
);
receiverOfEarnings = _receiverOfEarnings;
presaleToken = IERC20Metadata(_presaleToken);
tokenDecimals = presaleToken.decimals();
paused = true; //@dev start as paused
}
/**
* @notice Sets the address allowed to withdraw the proceeds from presale
* @param _receiverOfEarnings address of the reveiver
*/
function setReceiverOfEarnings(address payable _receiverOfEarnings)
external
onlyOwner
{
require(
_receiverOfEarnings != receiverOfEarnings,
"Receiver already configured"
);
require(_receiverOfEarnings != address(0), "Receiver cannot be 0");
receiverOfEarnings = _receiverOfEarnings;
}
/**
* @notice Sets new price for the presale token
* @param _price new price of the presale token - uses `DECIMALS` for precision
*/
function setPrice(uint256 _price) external onlyOwner {
require(_price != price, "New price cannot be same");
uint256 _oldPrice = price;
price = _price;
emit PriceChange(_oldPrice, _price);
}
/**
* @notice Releases presale tokens to the recipient
* @param _recipient recipient of the presale tokens
* @param _paidAmount amount paid by recipient
*/
function _releasePresaleTokens(
address _recipient,
uint256 _paidAmount
) internal {
uint256 tokensToReceive = calculateTokensToReceive(_paidAmount);
require(
tokensToReceive <= presaleToken.balanceOf(address(this)),
"Contract balance too low"
);
require(
presaleToken.transfer(_recipient, tokensToReceive),
"Token transfer failed"
);
}
receive() external payable {
buyTokensWithBNB();
}
/**
* @notice Allows purchase of presale tokens using BNB
*/
function buyTokensWithBNB()
public
payable
notPaused
nonReentrant
{
require(msg.value > 0, "No BNB sent");
_releasePresaleTokens(msg.sender, msg.value);
emit BoughtWithBNB(msg.value);
}
/**
* @notice Transfers collected funds to `receiverOfEarnings` address
*/
function withdraw() external {
require(
msg.sender == receiverOfEarnings,
"Sender not allowed to withdraw"
);
uint256 bnbBalance = address(this).balance;
if (bnbBalance > 0) {
payable(receiverOfEarnings).transfer(bnbBalance);
}
}
/**
* @notice Transfers all remaining `presaleToken` balance to owner when presale is over
*/
function rescuePresaleTokens() external onlyOwner isPaused {
uint256 balance = presaleToken.balanceOf(address(this));
require(balance > 0, "No tokens to rescue");
require(
presaleToken.transfer(owner(), balance),
"Token transfer failed"
);
}
/**
* @notice Calculates the amount of `presaleToken` based on the amount of `paidWithToken`
* @param _amount amount of `paidWithToken` used in purchase
*/
function calculateTokensToReceive(uint256 _amount)
public
view
returns (uint256)
{
uint256 amountToTransfer = (_amount * 10**tokenDecimals) / price;
return amountToTransfer;
}
/**
* @notice Pauses the presale
*/
function pause() external onlyOwner notPaused {
paused = true;
}
/**
* @notice Unpauses the presale
*/
function unpause() external onlyOwner isPaused {
paused = false;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
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
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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;
}
} | * @notice Transfers all remaining `presaleToken` balance to owner when presale is over/ | function rescuePresaleTokens() external onlyOwner isPaused {
uint256 balance = presaleToken.balanceOf(address(this));
require(balance > 0, "No tokens to rescue");
require(
presaleToken.transfer(owner(), balance),
"Token transfer failed"
);
}
| 13,788,903 | [
1,
1429,
18881,
777,
4463,
1375,
12202,
5349,
1345,
68,
11013,
358,
3410,
1347,
4075,
5349,
353,
1879,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
8223,
12236,
5349,
5157,
1435,
3903,
1338,
5541,
353,
28590,
288,
203,
3639,
2254,
5034,
11013,
273,
4075,
5349,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
2583,
12,
12296,
405,
374,
16,
315,
2279,
2430,
358,
8223,
8863,
203,
203,
3639,
2583,
12,
203,
5411,
4075,
5349,
1345,
18,
13866,
12,
8443,
9334,
11013,
3631,
203,
5411,
315,
1345,
7412,
2535,
6,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "./GraphTokenLock.sol";
/**
* @title GraphTokenLockSimple
* @notice This contract is the concrete simple implementation built on top of the base
* GraphTokenLock functionality for use when we only need the token lock schedule
* features but no interaction with the network.
*
* This contract is designed to be deployed without the use of a TokenManager.
*/
contract GraphTokenLockSimple is GraphTokenLock {
// Constructor
constructor() {
Ownable.initialize(msg.sender);
}
// Initializer
function initialize(
address _owner,
address _beneficiary,
address _token,
uint256 _managedAmount,
uint256 _startTime,
uint256 _endTime,
uint256 _periods,
uint256 _releaseStartTime,
uint256 _vestingCliffTime,
Revocability _revocable
) external onlyOwner {
_initialize(
_owner,
_beneficiary,
_token,
_managedAmount,
_startTime,
_endTime,
_periods,
_releaseStartTime,
_vestingCliffTime,
_revocable
);
}
}
| * @title GraphTokenLockSimple @notice This contract is the concrete simple implementation built on top of the base GraphTokenLock functionality for use when we only need the token lock schedule features but no interaction with the network. This contract is designed to be deployed without the use of a TokenManager./ Constructor | contract GraphTokenLockSimple is GraphTokenLock {
constructor() {
Ownable.initialize(msg.sender);
}
function initialize(
address _owner,
address _beneficiary,
address _token,
uint256 _managedAmount,
uint256 _startTime,
uint256 _endTime,
uint256 _periods,
uint256 _releaseStartTime,
uint256 _vestingCliffTime,
Revocability _revocable
) external onlyOwner {
_initialize(
_owner,
_beneficiary,
_token,
_managedAmount,
_startTime,
_endTime,
_periods,
_releaseStartTime,
_vestingCliffTime,
_revocable
);
}
}
| 12,826,269 | [
1,
4137,
1345,
2531,
5784,
225,
1220,
6835,
353,
326,
12220,
4143,
4471,
6650,
603,
1760,
434,
326,
1026,
5601,
1345,
2531,
14176,
364,
999,
1347,
732,
1338,
1608,
326,
1147,
2176,
4788,
4467,
1496,
1158,
13581,
598,
326,
2483,
18,
1220,
6835,
353,
26584,
358,
506,
19357,
2887,
326,
999,
434,
279,
3155,
1318,
18,
19,
11417,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
5601,
1345,
2531,
5784,
353,
5601,
1345,
2531,
288,
203,
203,
565,
3885,
1435,
288,
203,
3639,
14223,
6914,
18,
11160,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
203,
565,
445,
4046,
12,
203,
3639,
1758,
389,
8443,
16,
203,
3639,
1758,
389,
70,
4009,
74,
14463,
814,
16,
203,
3639,
1758,
389,
2316,
16,
203,
3639,
2254,
5034,
389,
19360,
6275,
16,
203,
3639,
2254,
5034,
389,
1937,
950,
16,
203,
3639,
2254,
5034,
389,
409,
950,
16,
203,
3639,
2254,
5034,
389,
20659,
16,
203,
3639,
2254,
5034,
389,
9340,
13649,
16,
203,
3639,
2254,
5034,
389,
90,
10100,
2009,
3048,
950,
16,
203,
3639,
14477,
504,
2967,
389,
9083,
504,
429,
203,
565,
262,
3903,
1338,
5541,
288,
203,
3639,
389,
11160,
12,
203,
5411,
389,
8443,
16,
203,
5411,
389,
70,
4009,
74,
14463,
814,
16,
203,
5411,
389,
2316,
16,
203,
5411,
389,
19360,
6275,
16,
203,
5411,
389,
1937,
950,
16,
203,
5411,
389,
409,
950,
16,
203,
5411,
389,
20659,
16,
203,
5411,
389,
9340,
13649,
16,
203,
5411,
389,
90,
10100,
2009,
3048,
950,
16,
203,
5411,
389,
9083,
504,
429,
203,
3639,
11272,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43113/0x22dFf84ee61f2c92fB1edD83A639f68362004c02/sources/contracts/NyanChef.sol | The HARMONYAN TOKEN! | HarmoNYANToken public HARMONYAN;
| 13,168,854 | [
1,
1986,
670,
985,
17667,
61,
1258,
14275,
5,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
670,
4610,
83,
50,
61,
1258,
1345,
1071,
670,
985,
17667,
61,
1258,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x61f30fd17eb78e9d65bac0ad0ac79f6e9aa51594
//Contract name: Crowdsale
//Balance: 0 Ether
//Verification Date: 11/10/2017
//Transacion Count: 8
// CODE STARTS HERE
/**
* @title METTA platform token & preICO crowdsale implementasion
* @author Maxim Akimov - <[email protected]>
* @author Dmitrii Bykov - <[email protected]>
*/
pragma solidity ^0.4.15;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @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;
address public ownerCandidat;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
ownerCandidat = newOwner;
}
/**
* @dev Allows safe change current owner to a newOwner.
*/
function confirmOwnership() onlyOwner {
require(msg.sender == ownerCandidat);
owner = msg.sender;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is StandardToken, Ownable {
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public onlyOwner {
require(_value > 0);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
event Burn(address indexed burner, uint indexed value);
}
contract MettaCoin is BurnableToken {
string public constant name = "TOKEN METTACOIN";
string public constant symbol = "METTACOIN";
uint32 public constant decimals = 18;
uint256 public constant initialSupply = 300000000 * 1 ether;
function MettaCoin() {
totalSupply = initialSupply;
balances[msg.sender] = initialSupply;
}
}
contract Crowdsale is Ownable {
using SafeMath for uint;
//
MettaCoin public token = new MettaCoin();
//
uint public start;
//
uint public period;
//
uint public rate;
//
uint public softcap;
//
uint public availableTokensforPreICO;
//
uint public countOfSaleTokens;
//
uint public currentPreICObalance;
//
uint public refererPercent;
//
mapping(address => uint) public balances;
// preICO manager data//////////////
address public managerETHaddress;
address public managerETHcandidatAddress;
uint public managerETHbonus;
/////////////////////////////////
function Crowdsale() {
// 1 METTACOIN = 0.00022 ETH
rate = 220000000000000;
//Mon, 10 Nov 2017 00:00:00 GMT
start = 1510272000;
// preICO period is 20 of november - 19 of december
period = 1; // 29
// minimum attracted ETH during preICO - 409
softcap = 440000000000000;//409 * 1 ether; //0.00044 for test
// maximum number mettacoins for preICO
availableTokensforPreICO = 8895539 * 1 ether;
// current ETH balance of preICO
currentPreICObalance = 0;
// how much mettacoins are sold
countOfSaleTokens = 0;
//percent for referer bonus program
refererPercent = 15;
//data of manager of company
managerETHaddress = 0x0;
managerETHbonus = 220000000000000; //35 ETH ~ 1,4 BTC // 35 * 1 ether;
}
/**
* @dev Initially safe sets preICO manager address
*/
function setPreIcoManager(address _addr) public onlyOwner {
require(managerETHaddress == 0x0) ;//ony once
managerETHcandidatAddress = _addr;
}
/**
* @dev Allows safe confirm of manager address
*/
function confirmManager() public {
require(msg.sender == managerETHcandidatAddress);
managerETHaddress = managerETHcandidatAddress;
}
/**
* @dev Allows safe changing of manager address
*/
function changeManager(address _addr) public {
require(msg.sender == managerETHaddress);
managerETHcandidatAddress = _addr;
}
/**
* @dev Indicates that preICO starts and not finishes
*/
modifier saleIsOn() {
require(now > start && now < start + period * 1 days);
_;
}
/**
* @dev Indicates that we have available tokens for sale
*/
modifier issetTokensForSale() {
require(countOfSaleTokens < availableTokensforPreICO);
_;
}
//test
function getEndDate1() returns (uint){
return start + period * 1 days;
}
function getENow() returns (uint){
return now;
}
///
/**
* @dev Tokens ans ownership will be transfered from preICO contract to ICO contract after preICO period.
*/
function TransferTokenToIcoContract(address ICOcontract) public onlyOwner {
require(now > start + period * 1 days);
token.transfer(ICOcontract, token.balanceOf(this));
token.transferOwnership(ICOcontract);
}
/**
* @dev Investments will be refunded if preICO not hits the softcap.
*/
function refund() public {
require(currentPreICObalance < softcap && now > start + period * 1 days);
msg.sender.transfer(balances[msg.sender]);
balances[msg.sender] = 0;
}
/**
* @dev Manager can get his/shes bonus after preICO reaches it's softcap
*/
function withdrawManagerBonus() public {
if(currentPreICObalance > softcap && managerETHbonus > 0){
managerETHaddress.transfer(managerETHbonus);
managerETHbonus = 0;
}
}
/**
* @dev If ICO reached owner can withdrow ETH for ICO comping managment
*/
function withdrawPreIcoFounds() public onlyOwner {
if(currentPreICObalance > softcap) {
// send all current ETH from contract to owner
uint availableToTranser = this.balance-managerETHbonus;
owner.transfer(availableToTranser);
}
}
/**
* @dev convert bytes to address
*/
function bytesToAddress(bytes source) internal returns(address) {
uint result;
uint mul = 1;
for(uint i = 20; i > 0; i--) {
result += uint8(source[i-1])*mul;
mul = mul*256;
}
return address(result);
}
function buyTokens() issetTokensForSale saleIsOn payable {
uint tokens = msg.value.mul(1 ether).div(rate);
if(tokens > 0) {
address referer = 0x0;
//-------------BONUSES-------------//
uint bonusTokens = 0;
if(now < start.add(7* 1 days)) {// 1st week
bonusTokens = tokens.mul(45).div(100); //+45%
} else if(now >= start.add(7 * 1 days) && now < start.add(14 * 1 days)) { // 2nd week
bonusTokens = tokens.mul(40).div(100); //+40%
} else if(now >= start.add(14* 1 days) && now < start.add(21 * 1 days)) { // 3th week
bonusTokens = tokens.mul(35).div(100); //+35%
} else if(now >= start.add(21* 1 days) && now < start.add(28 * 1 days)) { // 4th week
bonusTokens = tokens.mul(30).div(100); //+30%
}
tokens = tokens.add(bonusTokens);
//---------END-BONUSES-------------//
//---------referal program--------- //abailable after 3th week onli
// if(now >= start.add(14* 1 days) && now < start.add(28 * 1 days)) {
if(msg.data.length == 20) {
referer = bytesToAddress(bytes(msg.data));
require(referer != msg.sender);
uint refererTokens = tokens.mul(refererPercent).div(100);
}
// }
//---------end referal program---------//
if(availableTokensforPreICO > countOfSaleTokens.add(tokens)) {
token.transfer(msg.sender, tokens);
currentPreICObalance = currentPreICObalance.add(msg.value);
countOfSaleTokens = countOfSaleTokens.add(tokens);
balances[msg.sender] = balances[msg.sender].add(msg.value);
if(availableTokensforPreICO > countOfSaleTokens.add(tokens).add(refererTokens)){
// send token to referrer
if(referer !=0x0 && refererTokens >0){
token.transfer(referer, refererTokens);
countOfSaleTokens = countOfSaleTokens.add(refererTokens);
}
}
} else {
// there are not sufficient number of tokens - return of ETH
msg.sender.transfer(msg.value);
}
}else{
// retun to buyer if tokens == 0
msg.sender.transfer(msg.value);
}
}
function() external payable {
buyTokens();
}
}
| * @dev Tokens ans ownership will be transfered from preICO contract to ICO contract after preICO period./ | function TransferTokenToIcoContract(address ICOcontract) public onlyOwner {
require(now > start + period * 1 days);
token.transfer(ICOcontract, token.balanceOf(this));
token.transferOwnership(ICOcontract);
}
| 12,702,087 | [
1,
5157,
4152,
23178,
903,
506,
7412,
329,
628,
675,
2871,
51,
6835,
358,
467,
3865,
6835,
1839,
675,
2871,
51,
3879,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
12279,
1345,
774,
45,
2894,
8924,
12,
2867,
467,
3865,
16351,
13,
1071,
1338,
5541,
288,
203,
202,
202,
6528,
12,
3338,
405,
787,
397,
3879,
380,
404,
4681,
1769,
203,
202,
202,
2316,
18,
13866,
12,
2871,
51,
16351,
16,
1147,
18,
12296,
951,
12,
2211,
10019,
203,
202,
202,
2316,
18,
13866,
5460,
12565,
12,
2871,
51,
16351,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x0FcFbE6B420E31812F37725D82DCeA7cf16F1E72/sources/contracts/SHDCOGcollection.sol | * @dev Sets the maximum number of NFTs that can be sold to a specific address. @param limit The maximum number of NFTs that be bought by a wallet./ | function setWalletLimit(uint256 limit) external onlyOwner {
walletLimit = limit;
}
| 7,046,983 | [
1,
2785,
326,
4207,
1300,
434,
423,
4464,
87,
716,
848,
506,
272,
1673,
358,
279,
2923,
1758,
18,
225,
1800,
1021,
4207,
1300,
434,
423,
4464,
87,
716,
506,
800,
9540,
635,
279,
9230,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
16936,
3039,
12,
11890,
5034,
1800,
13,
3903,
1338,
5541,
288,
203,
3639,
9230,
3039,
273,
1800,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xdA3C33BA6328bed1A86295B1607bc2CFf69c5d18/sources/Snek.sol | SwapbackAnti-whale Fee receivers exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount | contract Snek is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private inSwapback;
bool public swapbackEnabled = false;
uint256 public minBalanceForSwapback;
uint256 public maxBalanceForSwapback;
bool public walletLimits = true;
bool public sameBlockDelay = true;
uint256 public mxWallet;
uint256 public mxTx;
mapping(address => uint256) private addressLastTransfer;
address public lpWallet;
address public marketingWallet;
address public devWallet;
bool public tradingEnabled = false;
uint256 public totalFeesBuy;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public totalFeesSell;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
mapping(address => bool) private _isFeeExempt;
mapping(address => bool) public _isTxLimitExempt;
mapping(address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event devWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
constructor() ERC20("Snek", "Snek") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 10;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 40;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1000000000 * 1e18;
mxTx = (totalSupply * 2) / 100;
mxWallet = (totalSupply * 2) / 100;
minBalanceForSwapback = (totalSupply * 5) / 10000;
maxBalanceForSwapback = (totalSupply * 100) / 1000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
totalFeesBuy = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
totalFeesSell = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = 0xdA2c1f1D5AD38Ecde8D28Fb0Ea3fe4A654C648C8;
devWallet = msg.sender;
lpWallet = msg.sender;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromFees(marketingWallet, true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
excludeFromMaxTransaction(marketingWallet, true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
}
receive() external payable {}
function enableTrading() external onlyOwner {
tradingEnabled = true;
swapbackEnabled = true;
}
function hiss() external onlyOwner {
tradingEnabled = true;
swapbackEnabled = true;
}
function removeLimits() external onlyOwner returns (bool) {
walletLimits = false;
return true;
}
function disableTransferDelay() external onlyOwner returns (bool) {
sameBlockDelay = false;
return true;
}
function updateSwapTokensAtAmount(uint256 newAmount)
external
onlyOwner
returns (bool)
{
require(
newAmount >= totalSupply()/ 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
require(
newAmount <= 500 * totalSupply()/ 100000,
"Swap amount cannot be higher than 0.5% total supply."
);
require(
newAmount <= maxBalanceForSwapback,
"Swap amount cannot be higher than maxBalanceForSwapback"
);
minBalanceForSwapback = newAmount;
return true;
}
function updateMaxTokensForSwapback(uint256 newAmount)
external
onlyOwner
returns (bool)
{
require(
newAmount >= minBalanceForSwapback,
"Swap amount cannot be lower than minBalanceForSwapback"
);
maxBalanceForSwapback = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(
newNum >= 2,
"Cannot set mxTx lower than 0.2%"
);
mxTx = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(
newNum >= 5,
"Cannot set mxWallet lower than 0.5%"
);
mxWallet = newNum * totalSupply()/1000;
}
function excludeFromMaxTransaction(address updAds, bool isEx)
public
onlyOwner
{
_isTxLimitExempt[updAds] = isEx;
}
function updateSwapEnabled(bool enabled) external onlyOwner {
swapbackEnabled = enabled;
}
function updateBuyFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
totalFeesBuy = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(totalFeesBuy <= 5, "Must keep fees at 5% or less");
}
function updateSellFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
totalFeesSell = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(totalFeesSell <= 5, "Must keep fees at 5% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isFeeExempt[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"The pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function setMarketingWallet(address newMarketingWallet)
external
onlyOwner
{
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function setLpWallet(address newLpWallet)
external
onlyOwner
{
lpWallet = newLpWallet;
}
function setDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isFeeExempt(address account) public view returns (bool) {
return _isFeeExempt[account];
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (walletLimits) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!inSwapback
) {
if (!tradingEnabled) {
require(
_isFeeExempt[from] || _isFeeExempt[to],
"Trading is not active."
);
}
if (sameBlockDelay) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
addressLastTransfer[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
addressLastTransfer[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isTxLimitExempt[to]
) {
require(
amount <= mxTx,
"Buy transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isTxLimitExempt[from]
) {
require(
amount <= mxTx,
"Sell transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minBalanceForSwapback;
if (
canSwap &&
swapbackEnabled &&
!inSwapback &&
!automatedMarketMakerPairs[from] &&
!_isFeeExempt[from] &&
!_isFeeExempt[to]
) {
inSwapback = true;
swapBack();
inSwapback = false;
}
bool takeFee = !inSwapback;
if (_isFeeExempt[from] || _isFeeExempt[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && totalFeesSell > 0) {
fees = amount.mul(totalFeesSell).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / totalFeesSell;
tokensForDev += (fees * sellDevFee) / totalFeesSell;
tokensForMarketing += (fees * sellMarketingFee) / totalFeesSell;
}
else if (automatedMarketMakerPairs[from] && totalFeesBuy > 0) {
fees = amount.mul(totalFeesBuy).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / totalFeesBuy;
tokensForDev += (fees * buyDevFee) / totalFeesBuy;
tokensForMarketing += (fees * buyMarketingFee) / totalFeesBuy;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (walletLimits) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!inSwapback
) {
if (!tradingEnabled) {
require(
_isFeeExempt[from] || _isFeeExempt[to],
"Trading is not active."
);
}
if (sameBlockDelay) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
addressLastTransfer[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
addressLastTransfer[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isTxLimitExempt[to]
) {
require(
amount <= mxTx,
"Buy transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isTxLimitExempt[from]
) {
require(
amount <= mxTx,
"Sell transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minBalanceForSwapback;
if (
canSwap &&
swapbackEnabled &&
!inSwapback &&
!automatedMarketMakerPairs[from] &&
!_isFeeExempt[from] &&
!_isFeeExempt[to]
) {
inSwapback = true;
swapBack();
inSwapback = false;
}
bool takeFee = !inSwapback;
if (_isFeeExempt[from] || _isFeeExempt[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && totalFeesSell > 0) {
fees = amount.mul(totalFeesSell).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / totalFeesSell;
tokensForDev += (fees * sellDevFee) / totalFeesSell;
tokensForMarketing += (fees * sellMarketingFee) / totalFeesSell;
}
else if (automatedMarketMakerPairs[from] && totalFeesBuy > 0) {
fees = amount.mul(totalFeesBuy).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / totalFeesBuy;
tokensForDev += (fees * buyDevFee) / totalFeesBuy;
tokensForMarketing += (fees * buyMarketingFee) / totalFeesBuy;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (walletLimits) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!inSwapback
) {
if (!tradingEnabled) {
require(
_isFeeExempt[from] || _isFeeExempt[to],
"Trading is not active."
);
}
if (sameBlockDelay) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
addressLastTransfer[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
addressLastTransfer[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isTxLimitExempt[to]
) {
require(
amount <= mxTx,
"Buy transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isTxLimitExempt[from]
) {
require(
amount <= mxTx,
"Sell transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minBalanceForSwapback;
if (
canSwap &&
swapbackEnabled &&
!inSwapback &&
!automatedMarketMakerPairs[from] &&
!_isFeeExempt[from] &&
!_isFeeExempt[to]
) {
inSwapback = true;
swapBack();
inSwapback = false;
}
bool takeFee = !inSwapback;
if (_isFeeExempt[from] || _isFeeExempt[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && totalFeesSell > 0) {
fees = amount.mul(totalFeesSell).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / totalFeesSell;
tokensForDev += (fees * sellDevFee) / totalFeesSell;
tokensForMarketing += (fees * sellMarketingFee) / totalFeesSell;
}
else if (automatedMarketMakerPairs[from] && totalFeesBuy > 0) {
fees = amount.mul(totalFeesBuy).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / totalFeesBuy;
tokensForDev += (fees * buyDevFee) / totalFeesBuy;
tokensForMarketing += (fees * buyMarketingFee) / totalFeesBuy;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (walletLimits) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!inSwapback
) {
if (!tradingEnabled) {
require(
_isFeeExempt[from] || _isFeeExempt[to],
"Trading is not active."
);
}
if (sameBlockDelay) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
addressLastTransfer[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
addressLastTransfer[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isTxLimitExempt[to]
) {
require(
amount <= mxTx,
"Buy transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isTxLimitExempt[from]
) {
require(
amount <= mxTx,
"Sell transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minBalanceForSwapback;
if (
canSwap &&
swapbackEnabled &&
!inSwapback &&
!automatedMarketMakerPairs[from] &&
!_isFeeExempt[from] &&
!_isFeeExempt[to]
) {
inSwapback = true;
swapBack();
inSwapback = false;
}
bool takeFee = !inSwapback;
if (_isFeeExempt[from] || _isFeeExempt[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && totalFeesSell > 0) {
fees = amount.mul(totalFeesSell).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / totalFeesSell;
tokensForDev += (fees * sellDevFee) / totalFeesSell;
tokensForMarketing += (fees * sellMarketingFee) / totalFeesSell;
}
else if (automatedMarketMakerPairs[from] && totalFeesBuy > 0) {
fees = amount.mul(totalFeesBuy).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / totalFeesBuy;
tokensForDev += (fees * buyDevFee) / totalFeesBuy;
tokensForMarketing += (fees * buyMarketingFee) / totalFeesBuy;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (walletLimits) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!inSwapback
) {
if (!tradingEnabled) {
require(
_isFeeExempt[from] || _isFeeExempt[to],
"Trading is not active."
);
}
if (sameBlockDelay) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
addressLastTransfer[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
addressLastTransfer[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isTxLimitExempt[to]
) {
require(
amount <= mxTx,
"Buy transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isTxLimitExempt[from]
) {
require(
amount <= mxTx,
"Sell transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minBalanceForSwapback;
if (
canSwap &&
swapbackEnabled &&
!inSwapback &&
!automatedMarketMakerPairs[from] &&
!_isFeeExempt[from] &&
!_isFeeExempt[to]
) {
inSwapback = true;
swapBack();
inSwapback = false;
}
bool takeFee = !inSwapback;
if (_isFeeExempt[from] || _isFeeExempt[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && totalFeesSell > 0) {
fees = amount.mul(totalFeesSell).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / totalFeesSell;
tokensForDev += (fees * sellDevFee) / totalFeesSell;
tokensForMarketing += (fees * sellMarketingFee) / totalFeesSell;
}
else if (automatedMarketMakerPairs[from] && totalFeesBuy > 0) {
fees = amount.mul(totalFeesBuy).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / totalFeesBuy;
tokensForDev += (fees * buyDevFee) / totalFeesBuy;
tokensForMarketing += (fees * buyMarketingFee) / totalFeesBuy;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (walletLimits) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!inSwapback
) {
if (!tradingEnabled) {
require(
_isFeeExempt[from] || _isFeeExempt[to],
"Trading is not active."
);
}
if (sameBlockDelay) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
addressLastTransfer[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
addressLastTransfer[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isTxLimitExempt[to]
) {
require(
amount <= mxTx,
"Buy transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isTxLimitExempt[from]
) {
require(
amount <= mxTx,
"Sell transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minBalanceForSwapback;
if (
canSwap &&
swapbackEnabled &&
!inSwapback &&
!automatedMarketMakerPairs[from] &&
!_isFeeExempt[from] &&
!_isFeeExempt[to]
) {
inSwapback = true;
swapBack();
inSwapback = false;
}
bool takeFee = !inSwapback;
if (_isFeeExempt[from] || _isFeeExempt[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && totalFeesSell > 0) {
fees = amount.mul(totalFeesSell).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / totalFeesSell;
tokensForDev += (fees * sellDevFee) / totalFeesSell;
tokensForMarketing += (fees * sellMarketingFee) / totalFeesSell;
}
else if (automatedMarketMakerPairs[from] && totalFeesBuy > 0) {
fees = amount.mul(totalFeesBuy).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / totalFeesBuy;
tokensForDev += (fees * buyDevFee) / totalFeesBuy;
tokensForMarketing += (fees * buyMarketingFee) / totalFeesBuy;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (walletLimits) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!inSwapback
) {
if (!tradingEnabled) {
require(
_isFeeExempt[from] || _isFeeExempt[to],
"Trading is not active."
);
}
if (sameBlockDelay) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
addressLastTransfer[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
addressLastTransfer[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isTxLimitExempt[to]
) {
require(
amount <= mxTx,
"Buy transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isTxLimitExempt[from]
) {
require(
amount <= mxTx,
"Sell transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minBalanceForSwapback;
if (
canSwap &&
swapbackEnabled &&
!inSwapback &&
!automatedMarketMakerPairs[from] &&
!_isFeeExempt[from] &&
!_isFeeExempt[to]
) {
inSwapback = true;
swapBack();
inSwapback = false;
}
bool takeFee = !inSwapback;
if (_isFeeExempt[from] || _isFeeExempt[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && totalFeesSell > 0) {
fees = amount.mul(totalFeesSell).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / totalFeesSell;
tokensForDev += (fees * sellDevFee) / totalFeesSell;
tokensForMarketing += (fees * sellMarketingFee) / totalFeesSell;
}
else if (automatedMarketMakerPairs[from] && totalFeesBuy > 0) {
fees = amount.mul(totalFeesBuy).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / totalFeesBuy;
tokensForDev += (fees * buyDevFee) / totalFeesBuy;
tokensForMarketing += (fees * buyMarketingFee) / totalFeesBuy;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
if (
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (walletLimits) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!inSwapback
) {
if (!tradingEnabled) {
require(
_isFeeExempt[from] || _isFeeExempt[to],
"Trading is not active."
);
}
if (sameBlockDelay) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
addressLastTransfer[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
addressLastTransfer[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isTxLimitExempt[to]
) {
require(
amount <= mxTx,
"Buy transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isTxLimitExempt[from]
) {
require(
amount <= mxTx,
"Sell transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minBalanceForSwapback;
if (
canSwap &&
swapbackEnabled &&
!inSwapback &&
!automatedMarketMakerPairs[from] &&
!_isFeeExempt[from] &&
!_isFeeExempt[to]
) {
inSwapback = true;
swapBack();
inSwapback = false;
}
bool takeFee = !inSwapback;
if (_isFeeExempt[from] || _isFeeExempt[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && totalFeesSell > 0) {
fees = amount.mul(totalFeesSell).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / totalFeesSell;
tokensForDev += (fees * sellDevFee) / totalFeesSell;
tokensForMarketing += (fees * sellMarketingFee) / totalFeesSell;
}
else if (automatedMarketMakerPairs[from] && totalFeesBuy > 0) {
fees = amount.mul(totalFeesBuy).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / totalFeesBuy;
tokensForDev += (fees * buyDevFee) / totalFeesBuy;
tokensForMarketing += (fees * buyMarketingFee) / totalFeesBuy;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
else if (
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (walletLimits) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!inSwapback
) {
if (!tradingEnabled) {
require(
_isFeeExempt[from] || _isFeeExempt[to],
"Trading is not active."
);
}
if (sameBlockDelay) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
addressLastTransfer[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
addressLastTransfer[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isTxLimitExempt[to]
) {
require(
amount <= mxTx,
"Buy transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isTxLimitExempt[from]
) {
require(
amount <= mxTx,
"Sell transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minBalanceForSwapback;
if (
canSwap &&
swapbackEnabled &&
!inSwapback &&
!automatedMarketMakerPairs[from] &&
!_isFeeExempt[from] &&
!_isFeeExempt[to]
) {
inSwapback = true;
swapBack();
inSwapback = false;
}
bool takeFee = !inSwapback;
if (_isFeeExempt[from] || _isFeeExempt[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && totalFeesSell > 0) {
fees = amount.mul(totalFeesSell).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / totalFeesSell;
tokensForDev += (fees * sellDevFee) / totalFeesSell;
tokensForMarketing += (fees * sellMarketingFee) / totalFeesSell;
}
else if (automatedMarketMakerPairs[from] && totalFeesBuy > 0) {
fees = amount.mul(totalFeesBuy).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / totalFeesBuy;
tokensForDev += (fees * buyDevFee) / totalFeesBuy;
tokensForMarketing += (fees * buyMarketingFee) / totalFeesBuy;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
} else if (!_isTxLimitExempt[to]) {
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (walletLimits) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!inSwapback
) {
if (!tradingEnabled) {
require(
_isFeeExempt[from] || _isFeeExempt[to],
"Trading is not active."
);
}
if (sameBlockDelay) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
addressLastTransfer[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
addressLastTransfer[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isTxLimitExempt[to]
) {
require(
amount <= mxTx,
"Buy transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isTxLimitExempt[from]
) {
require(
amount <= mxTx,
"Sell transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minBalanceForSwapback;
if (
canSwap &&
swapbackEnabled &&
!inSwapback &&
!automatedMarketMakerPairs[from] &&
!_isFeeExempt[from] &&
!_isFeeExempt[to]
) {
inSwapback = true;
swapBack();
inSwapback = false;
}
bool takeFee = !inSwapback;
if (_isFeeExempt[from] || _isFeeExempt[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && totalFeesSell > 0) {
fees = amount.mul(totalFeesSell).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / totalFeesSell;
tokensForDev += (fees * sellDevFee) / totalFeesSell;
tokensForMarketing += (fees * sellMarketingFee) / totalFeesSell;
}
else if (automatedMarketMakerPairs[from] && totalFeesBuy > 0) {
fees = amount.mul(totalFeesBuy).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / totalFeesBuy;
tokensForDev += (fees * buyDevFee) / totalFeesBuy;
tokensForMarketing += (fees * buyMarketingFee) / totalFeesBuy;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (walletLimits) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!inSwapback
) {
if (!tradingEnabled) {
require(
_isFeeExempt[from] || _isFeeExempt[to],
"Trading is not active."
);
}
if (sameBlockDelay) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
addressLastTransfer[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
addressLastTransfer[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isTxLimitExempt[to]
) {
require(
amount <= mxTx,
"Buy transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isTxLimitExempt[from]
) {
require(
amount <= mxTx,
"Sell transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minBalanceForSwapback;
if (
canSwap &&
swapbackEnabled &&
!inSwapback &&
!automatedMarketMakerPairs[from] &&
!_isFeeExempt[from] &&
!_isFeeExempt[to]
) {
inSwapback = true;
swapBack();
inSwapback = false;
}
bool takeFee = !inSwapback;
if (_isFeeExempt[from] || _isFeeExempt[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && totalFeesSell > 0) {
fees = amount.mul(totalFeesSell).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / totalFeesSell;
tokensForDev += (fees * sellDevFee) / totalFeesSell;
tokensForMarketing += (fees * sellMarketingFee) / totalFeesSell;
}
else if (automatedMarketMakerPairs[from] && totalFeesBuy > 0) {
fees = amount.mul(totalFeesBuy).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / totalFeesBuy;
tokensForDev += (fees * buyDevFee) / totalFeesBuy;
tokensForMarketing += (fees * buyMarketingFee) / totalFeesBuy;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (walletLimits) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!inSwapback
) {
if (!tradingEnabled) {
require(
_isFeeExempt[from] || _isFeeExempt[to],
"Trading is not active."
);
}
if (sameBlockDelay) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
addressLastTransfer[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
addressLastTransfer[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isTxLimitExempt[to]
) {
require(
amount <= mxTx,
"Buy transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isTxLimitExempt[from]
) {
require(
amount <= mxTx,
"Sell transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minBalanceForSwapback;
if (
canSwap &&
swapbackEnabled &&
!inSwapback &&
!automatedMarketMakerPairs[from] &&
!_isFeeExempt[from] &&
!_isFeeExempt[to]
) {
inSwapback = true;
swapBack();
inSwapback = false;
}
bool takeFee = !inSwapback;
if (_isFeeExempt[from] || _isFeeExempt[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && totalFeesSell > 0) {
fees = amount.mul(totalFeesSell).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / totalFeesSell;
tokensForDev += (fees * sellDevFee) / totalFeesSell;
tokensForMarketing += (fees * sellMarketingFee) / totalFeesSell;
}
else if (automatedMarketMakerPairs[from] && totalFeesBuy > 0) {
fees = amount.mul(totalFeesBuy).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / totalFeesBuy;
tokensForDev += (fees * buyDevFee) / totalFeesBuy;
tokensForMarketing += (fees * buyMarketingFee) / totalFeesBuy;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (walletLimits) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!inSwapback
) {
if (!tradingEnabled) {
require(
_isFeeExempt[from] || _isFeeExempt[to],
"Trading is not active."
);
}
if (sameBlockDelay) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
addressLastTransfer[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
addressLastTransfer[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isTxLimitExempt[to]
) {
require(
amount <= mxTx,
"Buy transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isTxLimitExempt[from]
) {
require(
amount <= mxTx,
"Sell transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minBalanceForSwapback;
if (
canSwap &&
swapbackEnabled &&
!inSwapback &&
!automatedMarketMakerPairs[from] &&
!_isFeeExempt[from] &&
!_isFeeExempt[to]
) {
inSwapback = true;
swapBack();
inSwapback = false;
}
bool takeFee = !inSwapback;
if (_isFeeExempt[from] || _isFeeExempt[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && totalFeesSell > 0) {
fees = amount.mul(totalFeesSell).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / totalFeesSell;
tokensForDev += (fees * sellDevFee) / totalFeesSell;
tokensForMarketing += (fees * sellMarketingFee) / totalFeesSell;
}
else if (automatedMarketMakerPairs[from] && totalFeesBuy > 0) {
fees = amount.mul(totalFeesBuy).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / totalFeesBuy;
tokensForDev += (fees * buyDevFee) / totalFeesBuy;
tokensForMarketing += (fees * buyMarketingFee) / totalFeesBuy;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (walletLimits) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!inSwapback
) {
if (!tradingEnabled) {
require(
_isFeeExempt[from] || _isFeeExempt[to],
"Trading is not active."
);
}
if (sameBlockDelay) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
addressLastTransfer[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
addressLastTransfer[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isTxLimitExempt[to]
) {
require(
amount <= mxTx,
"Buy transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isTxLimitExempt[from]
) {
require(
amount <= mxTx,
"Sell transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minBalanceForSwapback;
if (
canSwap &&
swapbackEnabled &&
!inSwapback &&
!automatedMarketMakerPairs[from] &&
!_isFeeExempt[from] &&
!_isFeeExempt[to]
) {
inSwapback = true;
swapBack();
inSwapback = false;
}
bool takeFee = !inSwapback;
if (_isFeeExempt[from] || _isFeeExempt[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && totalFeesSell > 0) {
fees = amount.mul(totalFeesSell).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / totalFeesSell;
tokensForDev += (fees * sellDevFee) / totalFeesSell;
tokensForMarketing += (fees * sellMarketingFee) / totalFeesSell;
}
else if (automatedMarketMakerPairs[from] && totalFeesBuy > 0) {
fees = amount.mul(totalFeesBuy).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / totalFeesBuy;
tokensForDev += (fees * buyDevFee) / totalFeesBuy;
tokensForMarketing += (fees * buyMarketingFee) / totalFeesBuy;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (walletLimits) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!inSwapback
) {
if (!tradingEnabled) {
require(
_isFeeExempt[from] || _isFeeExempt[to],
"Trading is not active."
);
}
if (sameBlockDelay) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
addressLastTransfer[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
addressLastTransfer[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isTxLimitExempt[to]
) {
require(
amount <= mxTx,
"Buy transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isTxLimitExempt[from]
) {
require(
amount <= mxTx,
"Sell transfer amount exceeds the mxTx."
);
require(
amount + balanceOf(to) <= mxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minBalanceForSwapback;
if (
canSwap &&
swapbackEnabled &&
!inSwapback &&
!automatedMarketMakerPairs[from] &&
!_isFeeExempt[from] &&
!_isFeeExempt[to]
) {
inSwapback = true;
swapBack();
inSwapback = false;
}
bool takeFee = !inSwapback;
if (_isFeeExempt[from] || _isFeeExempt[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && totalFeesSell > 0) {
fees = amount.mul(totalFeesSell).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / totalFeesSell;
tokensForDev += (fees * sellDevFee) / totalFeesSell;
tokensForMarketing += (fees * sellMarketingFee) / totalFeesSell;
}
else if (automatedMarketMakerPairs[from] && totalFeesBuy > 0) {
fees = amount.mul(totalFeesBuy).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / totalFeesBuy;
tokensForDev += (fees * buyDevFee) / totalFeesBuy;
tokensForMarketing += (fees * buyMarketingFee) / totalFeesBuy;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
lpWallet,
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > maxBalanceForSwapback) {
contractBalance = maxBalanceForSwapback;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > maxBalanceForSwapback) {
contractBalance = maxBalanceForSwapback;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > maxBalanceForSwapback) {
contractBalance = maxBalanceForSwapback;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) /
(success, ) = address(devWallet).call{value: ethForDev}("");
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > maxBalanceForSwapback) {
contractBalance = maxBalanceForSwapback;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > maxBalanceForSwapback) {
contractBalance = maxBalanceForSwapback;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
} | 3,104,481 | [
1,
12521,
823,
14925,
77,
17,
3350,
5349,
30174,
22686,
431,
17704,
1317,
628,
1656,
281,
471,
943,
2492,
3844,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
18961,
3839,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
7010,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
565,
1758,
1071,
5381,
8363,
1887,
273,
1758,
12,
20,
92,
22097,
1769,
203,
7010,
565,
1426,
3238,
316,
12521,
823,
31,
203,
565,
1426,
1071,
7720,
823,
1526,
273,
629,
31,
203,
565,
2254,
5034,
1071,
1131,
13937,
1290,
12521,
823,
31,
203,
565,
2254,
5034,
1071,
943,
13937,
1290,
12521,
823,
31,
203,
7010,
565,
1426,
1071,
9230,
12768,
273,
638,
31,
203,
565,
1426,
1071,
1967,
1768,
6763,
273,
638,
31,
203,
565,
2254,
5034,
1071,
7938,
16936,
31,
203,
565,
2254,
5034,
1071,
7938,
4188,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
1758,
3024,
5912,
31,
203,
7010,
565,
1758,
1071,
12423,
16936,
31,
203,
565,
1758,
1071,
13667,
310,
16936,
31,
203,
565,
1758,
1071,
4461,
16936,
31,
203,
7010,
565,
1426,
1071,
1284,
7459,
1526,
273,
629,
31,
203,
7010,
565,
2254,
5034,
1071,
2078,
2954,
281,
38,
9835,
31,
203,
565,
2254,
5034,
1071,
30143,
3882,
21747,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
48,
18988,
24237,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
8870,
14667,
31,
203,
7010,
565,
2254,
5034,
1071,
2078,
2954,
281,
55,
1165,
31,
203,
565,
2254,
5034,
1071,
357,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
/// Tenure is not within minimum and maximum authorized
/// @param tenure, actual tenure
/// @param minTenure, minimum tenure
/// @param maxTenure, maximum tenure
error InvalidTenure(uint16 tenure, uint16 minTenure, uint16 maxTenure);
/// AdvanceFee is higher than the maxAdvancedRatio
/// @param advanceFee, actual advanceFee
/// @param maxAdvancedRatio, maximum advanced ratio
error InvalidAdvanceFee(uint16 advanceFee, uint16 maxAdvancedRatio);
/// DiscountFee is lower than the minDiscountFee
/// @param discountFee, actual discountFee
/// @param minDiscountFee, minimum discount fee
error InvalidDiscountFee(uint16 discountFee, uint16 minDiscountFee);
/// FactoringFee is lower than the minDiscountFee
/// @param factoringFee, actual factoringFee
/// @param minFactoringFee, minimum factoring fee
error InvalidFactoringFee(uint16 factoringFee, uint16 minFactoringFee);
/// InvoiceAmount is not within minimum and maximum authorized
/// @param invoiceAmount, actual invoice amount
/// @param minAmount, minimum invoice amount
/// @param maxAmount, maximum invoice amount
error InvalidInvoiceAmount(uint invoiceAmount, uint minAmount, uint maxAmount);
/// Available Amount is higher than Invoice Amount
/// @param availableAmount, actual available amount
/// @param invoiceAmount, actual invoice amount
error InvalidAvailableAmount(uint availableAmount, uint invoiceAmount);
/// @title IOffer
/// @author Polytrade
interface IOffer {
struct OfferItem {
uint advancedAmount;
uint reserve;
uint64 disbursingAdvanceDate;
OfferParams params;
OfferRefunded refunded;
}
struct OfferParams {
uint8 gracePeriod;
uint16 tenure;
uint16 factoringFee;
uint16 discountFee;
uint16 advanceFee;
address stableAddress;
uint invoiceAmount;
uint availableAmount;
}
struct OfferRefunded {
uint16 lateFee;
uint64 dueDate;
uint24 numberOfLateDays;
uint totalCalculatedFees;
uint netAmount;
}
/**
* @dev Emitted when new offer is created
*/
event OfferCreated(uint indexed offerId, uint16 pricingId);
/**
* @dev Emitted when Reserve is refunded
*/
event ReserveRefunded(uint indexed offerId, uint refundedAmount);
/**
* @dev Emitted when PricingTable Address is updated
*/
event NewPricingTableContract(
address oldPricingTableAddress,
address newPricingTableAddress
);
/**
* @dev Emitted when PriceFeed Address is updated
*/
event NewPriceFeedContract(
address oldPriceFeedAddress,
address newPriceFeedAddress
);
/**
* @dev Emitted when Treasury Address is updated
*/
event NewTreasuryAddress(
address oldTreasuryAddress,
address newTreasuryAddress
);
/**
* @dev Emitted when LenderPool Address is updated
*/
event NewLenderPoolAddress(
address oldLenderPoolAddress,
address newLenderPoolAddress
);
/**
* @dev Emitted when Oracle usage is activated or deactivated
*/
event OracleUsageUpdated(bool status);
}
| * @dev Emitted when Oracle usage is activated or deactivated/ | event OracleUsageUpdated(bool status);
| 5,395,726 | [
1,
1514,
11541,
1347,
28544,
4084,
353,
14892,
578,
443,
18836,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
28544,
5357,
7381,
12,
6430,
1267,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
import "contracts/Issuer.sol";
import "contracts/NuCypherToken.sol";
import "contracts/proxy/Upgradeable.sol";
/**
* @dev Contract for testing internal methods in the Issuer contract
**/
contract IssuerMock is Issuer {
constructor(
NuCypherToken _token,
uint32 _hoursPerPeriod,
uint256 _miningCoefficient,
uint256 _lockedPeriodsCoefficient,
uint16 _rewardedPeriods
)
public
Issuer(
_token,
_hoursPerPeriod,
_miningCoefficient,
_lockedPeriodsCoefficient,
_rewardedPeriods
)
{
}
function testMint(
uint16 _period,
uint256 _lockedValue,
uint256 _totalLockedValue,
uint16 _allLockedPeriods
)
public returns (uint256 amount)
{
amount = mint(
_period,
_lockedValue,
_totalLockedValue,
_allLockedPeriods);
token.transfer(msg.sender, amount);
}
}
/**
* @notice Upgrade to this contract must lead to fail
**/
contract IssuerBad is Upgradeable {
address public token;
uint256 public miningCoefficient;
uint256 public lockedPeriodsCoefficient;
uint32 public secondsPerPeriod;
uint16 public rewardedPeriods;
uint16 public lastMintedPeriod;
// uint256 public currentSupply1;
uint256 public currentSupply2;
function verifyState(address) public {}
function finishUpgrade(address) public {}
}
/**
* @notice Contract for testing upgrading the Issuer contract
**/
contract IssuerV2Mock is Issuer {
uint256 public valueToCheck;
constructor(
NuCypherToken _token,
uint32 _hoursPerPeriod,
uint256 _miningCoefficient,
uint256 _lockedPeriodsCoefficient,
uint16 _rewardedPeriods
)
public
Issuer(
_token,
_hoursPerPeriod,
_miningCoefficient,
_lockedPeriodsCoefficient,
_rewardedPeriods
)
{
}
function setValueToCheck(uint256 _valueToCheck) public {
valueToCheck = _valueToCheck;
}
function verifyState(address _testTarget) public onlyOwner {
super.verifyState(_testTarget);
require(uint256(delegateGet(_testTarget, "valueToCheck()")) == valueToCheck);
}
}
| * @dev Contract for testing internal methods in the Issuer contract/ | contract IssuerMock is Issuer {
constructor(
NuCypherToken _token,
uint32 _hoursPerPeriod,
uint256 _miningCoefficient,
uint256 _lockedPeriodsCoefficient,
uint16 _rewardedPeriods
)
public
Issuer(
_token,
_hoursPerPeriod,
_miningCoefficient,
_lockedPeriodsCoefficient,
_rewardedPeriods
)
{
}
function testMint(
uint16 _period,
uint256 _lockedValue,
uint256 _totalLockedValue,
uint16 _allLockedPeriods
)
public returns (uint256 amount)
{
amount = mint(
_period,
_lockedValue,
_totalLockedValue,
_allLockedPeriods);
token.transfer(msg.sender, amount);
}
}
| 12,568,101 | [
1,
8924,
364,
7769,
2713,
2590,
316,
326,
23959,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
23959,
9865,
353,
23959,
288,
203,
203,
565,
3885,
12,
203,
3639,
20123,
17992,
21496,
1345,
389,
2316,
16,
203,
3639,
2254,
1578,
389,
16814,
2173,
5027,
16,
203,
3639,
2254,
5034,
389,
1154,
310,
4249,
25403,
16,
203,
3639,
2254,
5034,
389,
15091,
30807,
4249,
25403,
16,
203,
3639,
2254,
2313,
389,
266,
11804,
30807,
203,
565,
262,
203,
3639,
1071,
203,
3639,
23959,
12,
203,
5411,
389,
2316,
16,
203,
5411,
389,
16814,
2173,
5027,
16,
203,
5411,
389,
1154,
310,
4249,
25403,
16,
203,
5411,
389,
15091,
30807,
4249,
25403,
16,
203,
5411,
389,
266,
11804,
30807,
203,
3639,
262,
203,
565,
288,
203,
565,
289,
203,
203,
565,
445,
1842,
49,
474,
12,
203,
3639,
2254,
2313,
389,
6908,
16,
203,
3639,
2254,
5034,
389,
15091,
620,
16,
203,
3639,
2254,
5034,
389,
4963,
8966,
620,
16,
203,
3639,
2254,
2313,
389,
454,
8966,
30807,
203,
565,
262,
203,
3639,
1071,
1135,
261,
11890,
5034,
3844,
13,
203,
565,
288,
203,
3639,
3844,
273,
312,
474,
12,
203,
5411,
389,
6908,
16,
203,
5411,
389,
15091,
620,
16,
203,
5411,
389,
4963,
8966,
620,
16,
203,
5411,
389,
454,
8966,
30807,
1769,
203,
3639,
1147,
18,
13866,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
565,
289,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/3/0x3380C84F9944A562e935a9a177D9185fDA088382/sources/Market.sol | get wei amountproject KRK returncalculate feesupdate tablesoverall burned KRK - skipped!mint tokens | function purchaseTokens() external payable {
require(!mutex[msg.sender] || mutexTimeout[msg.sender]<block.number);
mutex[msg.sender] = true;
require(msg.value>0, "Zero purchase, at purchaseTokens");
uint weiAmount = msg.value;
uint krks = getKrkReturn(weiAmount);
require(circulatingKrk.add(krks)<=maxSell, "Purchase limit, at purchaseTokens, try smaller amounts or wait for buffer to clear.");
uint fee = getFourPercent(weiAmount);
uint krakintFee = fee.div(2);
uint investorFee = fee.sub(krakintFee);
uint afterFees = weiAmount.sub(fee);
circulatingKrk = circulatingKrk.add(krks);
krakintTotalEthEarnings = krakintTotalEthEarnings.add(krakintFee);
investorsCirculatingEthEarnings = investorsCirculatingEthEarnings.add(investorFee);
userEth[msg.sender] = userEth[msg.sender].add(afterFees);
circulatingUserKrk[msg.sender] = circulatingUserKrk[msg.sender].add(krks);
totalUserFees[msg.sender] = totalUserFees[msg.sender].add(fee);
totalMintedKRK = totalMintedKRK.add(krks);
totalDepositedEth = totalDepositedEth.add(weiAmount);
totalFeesPaid = totalFeesPaid.add(fee);
totalKrakintEarnings = totalKrakintEarnings.add(krakintFee);
totalInvestorsEarnings = totalInvestorsEarnings.add(investorFee);
totalDepositAfterFees = totalDepositAfterFees.add(afterFees);
mint(krks);
mutex[msg.sender] = false;
}
| 5,076,164 | [
1,
588,
732,
77,
3844,
4406,
1475,
54,
47,
327,
11162,
1656,
281,
2725,
4606,
27145,
18305,
329,
1475,
54,
47,
300,
9700,
5,
81,
474,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
915,
23701,
5157,
1435,
3903,
8843,
429,
288,
203,
202,
6528,
12,
5,
29946,
63,
3576,
18,
15330,
65,
747,
9020,
2694,
63,
3576,
18,
15330,
65,
32,
2629,
18,
2696,
1769,
203,
202,
29946,
63,
3576,
18,
15330,
65,
273,
638,
31,
203,
202,
203,
565,
2583,
12,
3576,
18,
1132,
34,
20,
16,
315,
7170,
23701,
16,
622,
23701,
5157,
8863,
203,
565,
2254,
732,
77,
6275,
273,
1234,
18,
1132,
31,
203,
377,
203,
565,
2254,
23953,
7904,
273,
16566,
86,
79,
990,
12,
1814,
77,
6275,
1769,
203,
565,
2583,
12,
11614,
1934,
1776,
47,
86,
79,
18,
1289,
12,
79,
86,
7904,
13,
32,
33,
1896,
55,
1165,
16,
315,
23164,
1800,
16,
622,
23701,
5157,
16,
775,
10648,
30980,
578,
2529,
364,
1613,
358,
2424,
1199,
1769,
203,
203,
565,
2254,
14036,
273,
2812,
477,
8410,
12,
1814,
77,
6275,
1769,
203,
565,
2254,
417,
354,
79,
474,
14667,
273,
14036,
18,
2892,
12,
22,
1769,
203,
565,
2254,
2198,
395,
280,
14667,
273,
14036,
18,
1717,
12,
79,
354,
79,
474,
14667,
1769,
203,
565,
2254,
1839,
2954,
281,
273,
732,
77,
6275,
18,
1717,
12,
21386,
1769,
203,
377,
203,
203,
565,
5886,
1934,
1776,
47,
86,
79,
273,
5886,
1934,
1776,
47,
86,
79,
18,
1289,
12,
79,
86,
7904,
1769,
203,
565,
417,
354,
79,
474,
5269,
41,
451,
41,
1303,
899,
273,
417,
354,
79,
474,
5269,
41,
451,
41,
1303,
899,
18,
1289,
12,
79,
354,
79,
474,
14667,
1769,
203,
565,
2
] |
pragma solidity ^0.4.24;
import {SafeMathLib} from "./safe-math-lib/contracts/SafeMathLib.sol";
import {Owned} from "./owned/contracts/Owned.sol";
/// @title Contract for holding funds in escrow between two semi trusted parties.
/// @author Piper Merriam <[email protected]>
contract Wallet is Owned {
using SafeMathLib for uint;
mapping (address => uint) allowances;
/// @dev Fallback function for depositing funds
function() public {
}
/// @dev Sends the recipient the specified amount
/// @notice This will send the reciepient the specified amount.
function send(address recipient, uint value) public onlyOwner returns (bool) {
return recipient.send(value);
}
/// @dev Sets recipient to be approved to withdraw the specified amount
/// @notice This will set the recipient to be approved to withdraw the specified amount.
function approve(address recipient, uint value) public onlyOwner returns (bool) {
allowances[recipient] = value;
return true;
}
/// @dev Lets caller withdraw up to their approved amount
/// @notice This will withdraw provided value, deducting it from your total allowance.
function withdraw(uint value) public returns (bool) {
allowances[msg.sender] = allowances[msg.sender].safeSub(value);
if (!msg.sender.send(value))
revert();
return true;
}
}
| @dev Lets caller withdraw up to their approved amount @notice This will withdraw provided value, deducting it from your total allowance. | function withdraw(uint value) public returns (bool) {
allowances[msg.sender] = allowances[msg.sender].safeSub(value);
if (!msg.sender.send(value))
revert();
return true;
}
| 1,031,427 | [
1,
48,
2413,
4894,
598,
9446,
731,
358,
3675,
20412,
3844,
225,
1220,
903,
598,
9446,
2112,
460,
16,
11140,
853,
310,
518,
628,
3433,
2078,
1699,
1359,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
12,
11890,
460,
13,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
1699,
6872,
63,
3576,
18,
15330,
65,
273,
1699,
6872,
63,
3576,
18,
15330,
8009,
4626,
1676,
12,
1132,
1769,
203,
3639,
309,
16051,
3576,
18,
15330,
18,
4661,
12,
1132,
3719,
203,
5411,
15226,
5621,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x4D9f950161346325CBdD88Cfb469f3378D1d94C6/sources/contracts/rewards/YOPRewards.sol | staking contract is for staking YOP tokens, so we can just use the decimals of YOP | function _getPoolDecimals(address _pool) internal view returns (uint8) {
if (_pool == stakingContract) {
return YOP_DECIMAL;
return IERC20MetadataUpgradeable(_pool).decimals();
}
}
| 5,017,108 | [
1,
334,
6159,
6835,
353,
364,
384,
6159,
1624,
3665,
2430,
16,
1427,
732,
848,
2537,
999,
326,
15105,
434,
1624,
3665,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
588,
2864,
31809,
12,
2867,
389,
6011,
13,
2713,
1476,
1135,
261,
11890,
28,
13,
288,
203,
565,
309,
261,
67,
6011,
422,
384,
6159,
8924,
13,
288,
203,
1377,
327,
1624,
3665,
67,
23816,
31,
203,
1377,
327,
467,
654,
39,
3462,
2277,
10784,
429,
24899,
6011,
2934,
31734,
5621,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-08-26
*/
pragma solidity ^0.5.16;
contract RewardPoolDelegationStorage {
// The FILST token address
address public filstAddress;
// The eFIL token address
address public efilAddress;
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active implementation
*/
address public implementation;
/**
* @notice Pending implementation
*/
address public pendingImplementation;
}
interface IRewardCalculator {
function calculate(uint filstAmount, uint fromBlockNumber) external view returns (uint);
}
interface IRewardStrategy {
// returns allocated result
function allocate(address staking, uint rewardAmount) external view returns (uint stakingPart, address[] memory others, uint[] memory othersParts);
}
interface IFilstManagement {
function getTotalMintedAmount() external view returns (uint);
function getMintedAmount(string calldata miner) external view returns (uint);
}
contract RewardPoolStorage is RewardPoolDelegationStorage {
// The IFilstManagement
IFilstManagement public management;
// The IRewardStrategy
IRewardStrategy public strategy;
// The IRewardCalculator contract
IRewardCalculator public calculator;
// The address of FILST Staking contract
address public staking;
// The last accrued block number
uint public accrualBlockNumber;
// The accrued reward for each participant
mapping(address => uint) public accruedRewards;
struct Debt {
// accrued index of debts
uint accruedIndex;
// accrued debts
uint accruedAmount;
// The last time the miner repay debts
uint lastRepaymentBlock;
}
// The last accrued index of debts
uint public debtAccruedIndex;
// The accrued debts for each miner
// minerId -> Debt
mapping(string => Debt) public minerDebts;
}
contract RewardPoolDelegator is RewardPoolDelegationStorage {
/**
* @notice Emitted when pendingImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingImplementation is accepted, which means implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
constructor(address filstAddress_, address efilAddress_) public {
filstAddress = filstAddress_;
efilAddress = efilAddress_;
// Set admin to caller
admin = msg.sender;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) external {
require(msg.sender == admin, "admin check");
address oldPendingImplementation = pendingImplementation;
pendingImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingImplementation);
}
/**
* @notice Accepts new implementation. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
*/
function _acceptImplementation() external {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
require(msg.sender == pendingImplementation && pendingImplementation != address(0), "pendingImplementation check");
// Save current values for inclusion in log
address oldImplementation = implementation;
address oldPendingImplementation = pendingImplementation;
implementation = pendingImplementation;
pendingImplementation = address(0);
emit NewImplementation(oldImplementation, implementation);
emit NewPendingImplementation(oldPendingImplementation, pendingImplementation);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
*/
function _setPendingAdmin(address newPendingAdmin) external {
require(msg.sender == admin, "admin check");
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() external {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(msg.sender == pendingAdmin && pendingAdmin != address(0), "pendingAdmin check");
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
function () payable external {
// delegate all other functions to current implementation
(bool success, ) = implementation.delegatecall(msg.data);
// solium-disable-next-line security/no-inline-assembly
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
}
// Copied from Compound/ExponentialNoError
/**
* @title Exponential module for storing fixed-precision decimals
* @author DeFil
* @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)});
}
}
interface Distributor {
// The asset to be distributed
function asset() external view returns (address);
// Return the accrued amount of account based on stored data
function accruedStored(address account) external view returns (uint);
// Accrue and distribute for caller, but not actually transfer assets to the caller
// returns the new accrued amount
function accrue() external returns (uint);
// Claim asset, transfer the given amount assets to receiver
function claim(address receiver, uint amount) external returns (uint);
}
// Copied from compound/EIP20Interface
/**
* @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);
}
// Copied from compound/EIP20NonStandardInterface
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
contract Redistributor is Distributor, ExponentialNoError {
/**
* @notice The superior Distributor contract
*/
Distributor public superior;
// The accrued amount of this address in superior Distributor
uint public superiorAccruedAmount;
// The initial accrual index
uint internal constant initialAccruedIndex = 1e36;
// The last accrued block number
uint public accrualBlockNumber;
// The last accrued index
uint public globalAccruedIndex;
// Total count of shares.
uint internal totalShares;
struct AccountState {
/// @notice The share of account
uint share;
// The last accrued index of account
uint accruedIndex;
/// @notice The accrued but not yet transferred to account
uint accruedAmount;
}
// The AccountState for each account
mapping(address => AccountState) internal accountStates;
/*** Events ***/
// Emitted when dfl is accrued
event Accrued(uint amount, uint globalAccruedIndex);
// Emitted when distribute to a account
event Distributed(address account, uint amount, uint accruedIndex);
// Emitted when account claims asset
event Claimed(address account, address receiver, uint amount);
// Emitted when account transfer asset
event Transferred(address from, address to, uint amount);
constructor(Distributor superior_) public {
// set superior
superior = superior_;
// init accrued index
globalAccruedIndex = initialAccruedIndex;
}
function asset() external view returns (address) {
return superior.asset();
}
// Return the accrued amount of account based on stored data
function accruedStored(address account) external view returns(uint) {
uint storedGlobalAccruedIndex;
if (totalShares == 0) {
storedGlobalAccruedIndex = globalAccruedIndex;
} else {
uint superiorAccruedStored = superior.accruedStored(address(this));
uint delta = sub_(superiorAccruedStored, superiorAccruedAmount);
Double memory ratio = fraction(delta, totalShares);
Double memory doubleGlobalAccruedIndex = add_(Double({mantissa: globalAccruedIndex}), ratio);
storedGlobalAccruedIndex = doubleGlobalAccruedIndex.mantissa;
}
(, uint instantAccountAccruedAmount) = accruedStoredInternal(account, storedGlobalAccruedIndex);
return instantAccountAccruedAmount;
}
// Return the accrued amount of account based on stored data
function accruedStoredInternal(address account, uint withGlobalAccruedIndex) internal view returns(uint, uint) {
AccountState memory state = accountStates[account];
Double memory doubleGlobalAccruedIndex = Double({mantissa: withGlobalAccruedIndex});
Double memory doubleAccountAccruedIndex = Double({mantissa: state.accruedIndex});
if (doubleAccountAccruedIndex.mantissa == 0 && doubleGlobalAccruedIndex.mantissa > 0) {
doubleAccountAccruedIndex.mantissa = initialAccruedIndex;
}
Double memory deltaIndex = sub_(doubleGlobalAccruedIndex, doubleAccountAccruedIndex);
uint delta = mul_(state.share, deltaIndex);
return (delta, add_(state.accruedAmount, delta));
}
function accrueInternal() internal {
uint blockNumber = getBlockNumber();
if (accrualBlockNumber == blockNumber) {
return;
}
uint newSuperiorAccruedAmount = superior.accrue();
if (totalShares == 0) {
accrualBlockNumber = blockNumber;
return;
}
uint delta = sub_(newSuperiorAccruedAmount, superiorAccruedAmount);
Double memory ratio = fraction(delta, totalShares);
Double memory doubleAccruedIndex = add_(Double({mantissa: globalAccruedIndex}), ratio);
// update globalAccruedIndex
globalAccruedIndex = doubleAccruedIndex.mantissa;
superiorAccruedAmount = newSuperiorAccruedAmount;
accrualBlockNumber = blockNumber;
emit Accrued(delta, doubleAccruedIndex.mantissa);
}
/**
* @notice accrue and returns accrued stored of msg.sender
*/
function accrue() external returns (uint) {
accrueInternal();
(, uint instantAccountAccruedAmount) = accruedStoredInternal(msg.sender, globalAccruedIndex);
return instantAccountAccruedAmount;
}
function distributeInternal(address account) internal {
(uint delta, uint instantAccruedAmount) = accruedStoredInternal(account, globalAccruedIndex);
AccountState storage state = accountStates[account];
state.accruedIndex = globalAccruedIndex;
state.accruedAmount = instantAccruedAmount;
// emit Distributed event
emit Distributed(account, delta, globalAccruedIndex);
}
function claim(address receiver, uint amount) external returns (uint) {
address account = msg.sender;
// keep fresh
accrueInternal();
distributeInternal(account);
AccountState storage state = accountStates[account];
require(amount <= state.accruedAmount, "claim: insufficient value");
// claim from superior
require(superior.claim(receiver, amount) == amount, "claim: amount mismatch");
// update storage
state.accruedAmount = sub_(state.accruedAmount, amount);
superiorAccruedAmount = sub_(superiorAccruedAmount, amount);
emit Claimed(account, receiver, amount);
return amount;
}
function claimAll() external {
address account = msg.sender;
// accrue and distribute
accrueInternal();
distributeInternal(account);
AccountState storage state = accountStates[account];
uint amount = state.accruedAmount;
// claim from superior
require(superior.claim(account, amount) == amount, "claim: amount mismatch");
// update storage
state.accruedAmount = 0;
superiorAccruedAmount = sub_(superiorAccruedAmount, amount);
emit Claimed(account, account, amount);
}
function transfer(address to, uint amount) external {
address from = msg.sender;
// keep fresh
accrueInternal();
distributeInternal(from);
AccountState storage fromState = accountStates[from];
uint actualAmount = amount;
if (actualAmount == 0) {
actualAmount = fromState.accruedAmount;
}
require(fromState.accruedAmount >= actualAmount, "transfer: insufficient value");
AccountState storage toState = accountStates[to];
// update storage
fromState.accruedAmount = sub_(fromState.accruedAmount, actualAmount);
toState.accruedAmount = add_(toState.accruedAmount, actualAmount);
emit Transferred(from, to, actualAmount);
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
}
contract Staking is Redistributor {
// The token to deposit
address public property;
/*** Events ***/
// Event emitted when new property tokens is deposited
event Deposit(address account, uint amount);
// Event emitted when new property tokens is withdrawed
event Withdraw(address account, uint amount);
constructor(address property_, Distributor superior_) Redistributor(superior_) public {
property = property_;
}
function totalDeposits() external view returns (uint) {
return totalShares;
}
function accountState(address account) external view returns (uint, uint, uint) {
AccountState memory state = accountStates[account];
return (state.share, state.accruedIndex, state.accruedAmount);
}
// Deposit property tokens
function deposit(uint amount) external returns (uint) {
address account = msg.sender;
// accrue & distribute
accrueInternal();
distributeInternal(account);
// transfer property token in
uint actualAmount = doTransferIn(account, amount);
// update storage
AccountState storage state = accountStates[account];
totalShares = add_(totalShares, actualAmount);
state.share = add_(state.share, actualAmount);
emit Deposit(account, actualAmount);
return actualAmount;
}
// Withdraw property tokens
function withdraw(uint amount) external returns (uint) {
address account = msg.sender;
AccountState storage state = accountStates[account];
require(state.share >= amount, "withdraw: insufficient value");
// accrue & distribute
accrueInternal();
distributeInternal(account);
// decrease total deposits
totalShares = sub_(totalShares, amount);
state.share = sub_(state.share, amount);
// transfer property tokens back to account
doTransferOut(account, amount);
emit Withdraw(account, amount);
return amount;
}
/*** Safe Token ***/
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(property);
uint balanceBefore = EIP20Interface(property).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(property).balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(property);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
}
contract RewardPool is RewardPoolStorage, Distributor, ExponentialNoError {
// The initial accrual index
uint internal constant initialAccruedIndex = 1e36;
/*** Events ***/
// Emitted when accrued rewards
event Accrued(uint stakingPart, address[] others, uint[] othersParts, uint debtAccruedIndex);
// Emitted when claimed rewards
event Claimed(address account, address receiver, uint amount);
// Emitted when distributed debt to miner
event DistributedDebt(string miner, uint debtDelta, uint accruedIndex);
// Emitted when repayment happend
event Repayment(string miner, address repayer, uint amount);
// Emitted when account transfer rewards
event Transferred(address from, address to, uint amount);
// Emitted when strategy is changed
event StrategyChanged(IRewardStrategy oldStrategy, IRewardStrategy newStrategy);
// Emitted when calcaultor is changed
event CalculatorChanged(IRewardCalculator oldCalculator, IRewardCalculator newCalculator);
// Emitted when staking is changed
event StakingChanged(address oldStaking, address newStaking);
// Emitted when management is changed
event ManagementChanged(IFilstManagement oldManagement, IFilstManagement newManagement);
// Emitted when liquditity is added
event LiqudityAdded(address benefactor, address admin, uint addAmount);
constructor() public { }
function asset() external view returns (address) {
return efilAddress;
}
// Return the accrued reward of account based on stored data
function accruedStored(address account) external view returns (uint) {
if (accrualBlockNumber == getBlockNumber() || Staking(staking).totalDeposits() == 0) {
return accruedRewards[account];
}
uint totalFilst = management.getTotalMintedAmount();
// calculate rewards
uint deltaRewards = calculator.calculate(totalFilst, accrualBlockNumber);
// allocate rewards
(uint stakingPart, address[] memory others, uint[] memory othersParts) = strategy.allocate(staking, deltaRewards);
require(others.length == othersParts.length, "IRewardStrategy.allocalte: others length mismatch");
if (staking == account) {
return add_(accruedRewards[staking], stakingPart);
} else {
// add accrued rewards for others
uint sumAllocation = stakingPart;
uint accountAccruedReward = accruedRewards[account];
for (uint i = 0; i < others.length; i ++) {
sumAllocation = add_(sumAllocation, othersParts[i]);
if (others[i] == account) {
accountAccruedReward = add_(accountAccruedReward, othersParts[i]);
}
}
require(sumAllocation == deltaRewards, "sumAllocation mismatch");
return accountAccruedReward;
}
}
// Accrue and distribute for caller, but not actually transfer rewards to the caller
// returns the new accrued amount
function accrue() public returns (uint) {
uint blockNumber = getBlockNumber();
if (accrualBlockNumber == blockNumber) {
return accruedRewards[msg.sender];
}
if (Staking(staking).totalDeposits() == 0) {
accrualBlockNumber = blockNumber;
return accruedRewards[msg.sender];
}
// total number of FILST that participates in dividends
uint totalFilst = management.getTotalMintedAmount();
// calculate rewards
uint deltaRewards = calculator.calculate(totalFilst, accrualBlockNumber);
// allocate rewards
(uint stakingPart, address[] memory others, uint[] memory othersParts) = strategy.allocate(staking, deltaRewards);
require(others.length == othersParts.length, "IRewardStrategy.allocalte: others length mismatch");
// add accrued rewards for staking
accruedRewards[staking] = add_(accruedRewards[staking], stakingPart);
// add accrued rewards for others
uint sumAllocation = stakingPart;
for (uint i = 0; i < others.length; i ++) {
sumAllocation = add_(sumAllocation, othersParts[i]);
accruedRewards[others[i]] = add_(accruedRewards[others[i]], othersParts[i]);
}
require(sumAllocation == deltaRewards, "sumAllocation mismatch");
// accure debts
accureDebtInternal(deltaRewards);
// update accrualBlockNumber
accrualBlockNumber = blockNumber;
// emint event
emit Accrued(stakingPart, others, othersParts, debtAccruedIndex);
return accruedRewards[msg.sender];
}
function accureDebtInternal(uint deltaDebts) internal {
// require(accrualBlockNumber == getBlockNumber(), "freshness check");
uint totalFilst = management.getTotalMintedAmount();
Double memory ratio = fraction(deltaDebts, totalFilst);
Double memory doubleAccruedIndex = add_(Double({mantissa: debtAccruedIndex}), ratio);
// update debtAccruedIndex
debtAccruedIndex = doubleAccruedIndex.mantissa;
}
// Return the accrued debts of miner based on stored data
function accruedDebtStored(string calldata miner) external view returns(uint) {
uint storedGlobalAccruedIndex;
if (accrualBlockNumber == getBlockNumber() || Staking(staking).totalDeposits() == 0) {
storedGlobalAccruedIndex = debtAccruedIndex;
} else {
uint totalFilst = management.getTotalMintedAmount();
uint deltaDebts = calculator.calculate(totalFilst, accrualBlockNumber);
Double memory ratio = fraction(deltaDebts, totalFilst);
Double memory doubleAccruedIndex = add_(Double({mantissa: debtAccruedIndex}), ratio);
storedGlobalAccruedIndex = doubleAccruedIndex.mantissa;
}
(, uint instantAccruedAmount) = accruedDebtStoredInternal(miner, storedGlobalAccruedIndex);
return instantAccruedAmount;
}
// Return the accrued debt of miner based on stored data
function accruedDebtStoredInternal(string memory miner, uint withDebtAccruedIndex) internal view returns(uint, uint) {
Debt memory debt = minerDebts[miner];
Double memory doubleDebtAccruedIndex = Double({mantissa: withDebtAccruedIndex});
Double memory doubleMinerAccruedIndex = Double({mantissa: debt.accruedIndex});
if (doubleMinerAccruedIndex.mantissa == 0 && doubleDebtAccruedIndex.mantissa > 0) {
doubleMinerAccruedIndex.mantissa = initialAccruedIndex;
}
uint minerMintedAmount = management.getMintedAmount(miner);
Double memory deltaIndex = sub_(doubleDebtAccruedIndex, doubleMinerAccruedIndex);
uint delta = mul_(minerMintedAmount, deltaIndex);
return (delta, add_(debt.accruedAmount, delta));
}
// accrue and distribute debt for given miner
function accrue(string memory miner) public {
accrue();
distributeDebtInternal(miner);
}
function distributeDebtInternal(string memory miner) internal {
(uint delta, uint instantAccruedAmount) = accruedDebtStoredInternal(miner, debtAccruedIndex);
Debt storage debt = minerDebts[miner];
debt.accruedIndex = debtAccruedIndex;
debt.accruedAmount = instantAccruedAmount;
// emit Distributed event
emit DistributedDebt(miner, delta, debtAccruedIndex);
}
// Claim rewards, transfer given amount rewards to receiver
function claim(address receiver, uint amount) external returns (uint) {
address account = msg.sender;
// keep fresh
accrue();
uint accruedReward = accruedRewards[account];
require(accruedReward >= amount, "Insufficient value");
// transfer reward to receiver
transferRewardOut(receiver, amount);
// update storage
accruedRewards[account] = sub_(accruedReward, amount);
emit Claimed(account, receiver, amount);
return amount;
}
// Claim all accrued rewards
function claimAll() external returns (uint) {
address account = msg.sender;
// keep fresh
accrue();
uint accruedReward = accruedRewards[account];
// transfer
transferRewardOut(account, accruedReward);
// update storage
accruedRewards[account] = 0;
emit Claimed(account, account, accruedReward);
}
function transferRewardOut(address account, uint amount) internal {
EIP20Interface efil = EIP20Interface(efilAddress);
uint remaining = efil.balanceOf(address(this));
require(remaining >= amount, "Insufficient cash");
efil.transfer(account, amount);
}
// repay given amount of debts for miner
function repayDebt(string calldata miner, uint amount) external {
address repayer = msg.sender;
// keep fresh (distribute debt for miner)
accrue(miner);
// reference storage
Debt storage debt = minerDebts[miner];
uint actualAmount = amount;
if (actualAmount > debt.accruedAmount) {
actualAmount = debt.accruedAmount;
}
EIP20Interface efil = EIP20Interface(efilAddress);
require(efil.transferFrom(repayer, address(this), actualAmount), "transferFrom failed");
debt.accruedAmount = sub_(debt.accruedAmount, actualAmount);
debt.lastRepaymentBlock = getBlockNumber();
emit Repayment(miner, repayer, actualAmount);
}
function transfer(address to, uint amount) external {
address from = msg.sender;
// keep fresh
accrue();
uint actualAmount = amount;
if (actualAmount == 0) {
actualAmount = accruedRewards[from];
}
require(accruedRewards[from] >= actualAmount, "Insufficient value");
// update storage
accruedRewards[from] = sub_(accruedRewards[from], actualAmount);
accruedRewards[to] = add_(accruedRewards[to], actualAmount);
emit Transferred(from, to, actualAmount);
}
/*** Admin Functions ***/
// set management contract
function setManagement(IFilstManagement newManagement) external {
require(msg.sender == admin, "admin check");
require(address(newManagement) != address(0), "Invalid newManagement");
if (debtAccruedIndex == 0) {
debtAccruedIndex = initialAccruedIndex;
}
// save old for event
IFilstManagement oldManagement = management;
// update
management = newManagement;
emit ManagementChanged(oldManagement, newManagement);
}
// set strategy contract
function setStrategy(IRewardStrategy newStrategy) external {
require(msg.sender == admin, "admin check");
require(address(newStrategy) != address(0), "Invalid newStrategy");
// save old for event
IRewardStrategy oldStrategy = strategy;
// update
strategy = newStrategy;
emit StrategyChanged(oldStrategy, newStrategy);
}
// set calculator contract
function setCalculator(IRewardCalculator newCalculator) external {
require(msg.sender == admin, "admin check");
require(address(newCalculator) != address(0), "Invalid newCalculator");
// save old for event
IRewardCalculator oldCalculator = calculator;
// update
calculator = newCalculator;
emit CalculatorChanged(oldCalculator, newCalculator);
}
// set staking contract
function setStaking(address newStaking) external {
require(msg.sender == admin, "admin check");
require(address(Staking(newStaking).superior()) == address(this), "Staking superior mismatch");
require(Staking(newStaking).property() == filstAddress, "Staking property mismatch");
require(Staking(newStaking).asset() == efilAddress, "Staking asset mismatch");
// save old for event
address oldStaking = staking;
// update
staking = newStaking;
emit StakingChanged(oldStaking, newStaking);
}
// add eFIL to pool
function addLiqudity(uint amount) external {
// transfer in
require(EIP20Interface(efilAddress).transferFrom(msg.sender, address(this), amount), "transfer in failed");
// added accrued rewards to admin
accruedRewards[admin] = add_(accruedRewards[admin], amount);
emit LiqudityAdded(msg.sender, admin, amount);
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
function _become(RewardPoolDelegator delegator) public {
require(msg.sender == delegator.admin(), "only delegator admin can change implementation");
delegator._acceptImplementation();
}
} | emit Distributed event | function distributeDebtInternal(string memory miner) internal {
(uint delta, uint instantAccruedAmount) = accruedDebtStoredInternal(miner, debtAccruedIndex);
Debt storage debt = minerDebts[miner];
debt.accruedIndex = debtAccruedIndex;
debt.accruedAmount = instantAccruedAmount;
emit DistributedDebt(miner, delta, debtAccruedIndex);
}
| 10,861,806 | [
1,
18356,
27877,
871,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
25722,
758,
23602,
3061,
12,
1080,
3778,
1131,
264,
13,
2713,
288,
203,
3639,
261,
11890,
3622,
16,
2254,
5934,
8973,
86,
5957,
6275,
13,
273,
4078,
86,
5957,
758,
23602,
18005,
3061,
12,
1154,
264,
16,
18202,
88,
8973,
86,
5957,
1016,
1769,
203,
203,
3639,
1505,
23602,
2502,
18202,
88,
273,
1131,
264,
758,
70,
3428,
63,
1154,
264,
15533,
203,
3639,
18202,
88,
18,
8981,
86,
5957,
1016,
273,
18202,
88,
8973,
86,
5957,
1016,
31,
203,
3639,
18202,
88,
18,
8981,
86,
5957,
6275,
273,
5934,
8973,
86,
5957,
6275,
31,
203,
203,
3639,
3626,
27877,
758,
23602,
12,
1154,
264,
16,
3622,
16,
18202,
88,
8973,
86,
5957,
1016,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.